├── tutorials
├── 3_functions.md
├── index.md
├── 2_control_flow.md
└── 1_basic.md
├── documentacion.pdf
├── test.sqy
├── .github
└── ISSUE_TEMPLATE
│ ├── feature_request.md
│ └── bug_report.md
├── bench.py
├── main.py
├── code.sqy
├── visualiser.py
├── codegen.py
├── lexer.py
├── ir_code.md
├── myeval.py
├── example.md
├── README.md
├── parser.py
└── LICENSE
/tutorials/3_functions.md:
--------------------------------------------------------------------------------
1 | # Functions
2 |
3 |
4 |
--------------------------------------------------------------------------------
/documentacion.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mv-lab/Squanchy-PL/HEAD/documentacion.pdf
--------------------------------------------------------------------------------
/tutorials/index.md:
--------------------------------------------------------------------------------
1 | ## Squanchy Tutorial Index
2 | ---
3 | [About Squanchy](../README.md)
4 |
5 | [1. Basic Concepts](1_basic.md)
6 |
7 | [2. Control Flow](2_control_flow.md)
8 |
9 | [3. Functions](3_functions.md)
10 |
11 | [4. Code Example](../example.md)
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/test.sqy:
--------------------------------------------------------------------------------
1 | # CODE GENERATION EXAMPLE IN SQUANCHY#
2 | # ------------------------------------------------#
3 |
4 | print (1, " hola mundo en Squanchy")
5 |
6 | 425+5266
7 |
8 | 2636-5263+5
9 |
10 | +1*53-4262
11 |
12 | a:5
13 | b:c:d:10
14 |
15 | print ("a = ",a," b = ",b," c= ",c," d= ",d)
16 |
17 | print(a+b-c*d)
18 | print ("b+c = c+d ",b+c = c+d)
19 | print ("a+b < c+d ",a+b < c+d)
20 | print ("a+b > c+d ",a+b > c+d)
21 |
22 | print (400/5+20-15/3)
23 | print (253 and 253)
24 | print (10 or 16)
25 |
26 | # some functions #
27 |
28 | suma (a,b) -> a+b
29 |
30 | resta (a,b) -> a-b
31 |
32 | operation (a,b,c) -> a-b*c
33 |
34 |
35 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/feature_request.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Feature request
3 | about: Suggest an idea for this project
4 | title: ''
5 | labels: ''
6 | assignees: ''
7 |
8 | ---
9 |
10 | **Is your feature request related to a problem? Please describe.**
11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
12 |
13 | **Describe the solution you'd like**
14 | A clear and concise description of what you want to happen.
15 |
16 | **Describe alternatives you've considered**
17 | A clear and concise description of any alternative solutions or features you've considered.
18 |
19 | **Additional context**
20 | Add any other context or screenshots about the feature request here.
21 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/bug_report.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Bug report
3 | about: Create a report to help us improve
4 | title: ''
5 | labels: ''
6 | assignees: ''
7 |
8 | ---
9 |
10 | **Describe the bug**
11 | A clear and concise description of what the bug is.
12 |
13 | **To Reproduce**
14 | Steps to reproduce the behavior:
15 | 1. Go to '...'
16 | 2. Click on '....'
17 | 3. Scroll down to '....'
18 | 4. See error
19 |
20 | **Expected behavior**
21 | A clear and concise description of what you expected to happen.
22 |
23 | **Screenshots**
24 | If applicable, add screenshots to help explain your problem.
25 |
26 | **Desktop (please complete the following information):**
27 | - OS: [e.g. iOS]
28 | - Browser [e.g. chrome, safari]
29 | - Version [e.g. 22]
30 |
31 | **Smartphone (please complete the following information):**
32 | - Device: [e.g. iPhone6]
33 | - OS: [e.g. iOS8.1]
34 | - Browser [e.g. stock browser, safari]
35 | - Version [e.g. 22]
36 |
37 | **Additional context**
38 | Add any other context about the problem here.
39 |
--------------------------------------------------------------------------------
/bench.py:
--------------------------------------------------------------------------------
1 | #-------------------------------------------------------------------------------
2 | # Copyright (C) 2018 Gabriel Rodriguez Canal
3 | # Copyright (C) 2018 Marcos V. Conde
4 | #
5 | # This program is free software: you can redistribute it and/or modify
6 | # it under the terms of the GNU General Public License as published by
7 | # the Free Software Foundation, either version 3 of the License, or
8 | # (at your option) any later version.
9 | #
10 | # This program is distributed in the hope that it will be useful,
11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | # GNU General Public License for more details.
14 | #
15 | # You should have received a copy of the GNU General Public License
16 | # along with this program. If not, see .
17 | #-------------------------------------------------------------------------------
18 |
19 |
20 | import time
21 | import compiler
22 |
23 |
24 | def main ():
25 |
26 | measure = []
27 | program = open("code.txt").read()
28 | program = program.replace("\n","\\n")
29 | program = program.replace("\t","\\t")
30 |
31 | for i in range (1000):
32 | start = time.time()
33 | compiler.parseFile("code_py.txt")
34 | end = time.time()
35 | measure.append(end-start)
36 |
37 | sqyt = float(sum(measure)/len(measure))
38 | print "py time >>",sqyt
39 |
40 |
41 | main()
42 |
43 |
44 |
45 |
--------------------------------------------------------------------------------
/main.py:
--------------------------------------------------------------------------------
1 | #-------------------------------------------------------------------------------
2 | # Copyright (C) 2018 Marcos V. Conde
3 | #
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 | #
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU General Public License for more details.
13 | #
14 | # You should have received a copy of the GNU General Public License
15 | # along with this program. If not, see .
16 | #-------------------------------------------------------------------------------
17 |
18 |
19 | import llvmlite.ir as ir
20 | import llvmlite.binding as llvm
21 | from sqyparser import ast
22 | from codegen import CodeGen
23 | import myeval as e
24 | import os
25 |
26 |
27 | def console ():
28 |
29 | try:
30 | while True:
31 | expr = input (">> ")
32 | if expr == "exit": exit()
33 | if expr == "clear":
34 | os.system('clear')
35 | console()
36 |
37 | program,scope = ast(expr)
38 | tree = program.first[0]
39 | print (tree)
40 | print (scope)
41 | print (e.Eval(tree,scope))
42 |
43 | except Exception as e:
44 | print (e.args[0])
45 | console()
46 |
47 |
48 |
49 | f = open("test.sqy")
50 | program = f.read()
51 | f.close()
52 | program = program.replace("\n","\\n").replace("\t","\\t")
53 |
54 | tree,scope = ast(program)
55 | print ("\n",tree)
56 | print ("\n",scope,"\n")
57 |
58 | #console()
59 |
60 | codegen = CodeGen()
61 |
62 | module = codegen.module
63 | builder = codegen.builder
64 | printf = codegen.printf
65 |
66 | for i in tree.first:
67 | #print (">>", i)
68 | e.Eval(i,scope,builder,module,printf)
69 |
70 |
71 | codegen.create_ir()
72 | codegen.save_ir("output.ll")
73 | tm = llvm.Target.from_default_triple().create_target_machine()
74 |
75 | os.system('llc -filetype=obj output.ll')
76 | os.system('clang output.o -o output')
77 | os.system('cat output.ll')
78 | #os.system('./output')
--------------------------------------------------------------------------------
/code.sqy:
--------------------------------------------------------------------------------
1 | # CODE EXAMPLE IN SQUANCHY#
2 | # ------------------------------------------------#
3 |
4 |
5 | # prueba de comentario
6 | multilnea#
7 |
8 |
9 | # OPERATORS #
10 |
11 | a+b*c**2-(-1/2)
12 |
13 | x:5+6
14 | x:y:z:8
15 |
16 | not a or b and c
17 |
18 | e-05
19 |
20 | pi
21 |
22 | var_1 : 56
23 |
24 | tuple : (a,b,c)
25 |
26 | True and False
27 |
28 | (a<<2)+1
29 |
30 |
31 | # LISTS #
32 |
33 | numbers : [1,2,3,4]
34 | truths : [True,False,False]
35 | strings : ["here","are","some","strings"]
36 |
37 | list : [1,2,3,4,5,"hello"]
38 | mylist : [12,45463,1.56,"hello",
39 | 45,35,57]
40 |
41 | list_of_list : [1,2,3,[1,2,3]]
42 |
43 |
44 | multiline_list : [
45 | a,b,c,
46 | d,e,f,
47 | 1,2,3,
48 | "hi!",5.76,True
49 | ]
50 |
51 |
52 | # TUPLES #
53 |
54 | my_Tuple: ("Hello world", False)
55 | my_tuple : (1,"hello",5.6)
56 | ((2,3), True)
57 | ((2,3), [2,3])
58 | [(1,2), (3,4), (5,6)]
59 |
60 |
61 | mylist.1
62 | my_tuple.3
63 |
64 | # GLOBAL #
65 |
66 | global u
67 | global v
68 |
69 |
70 | # CONSTANTS #
71 |
72 | a := 5
73 | b := True
74 | c := "constant"
75 |
76 |
77 | # LAMBDA #
78 |
79 | add : lambda a b :: a+b
80 | lambda r :: r**2*pi
81 |
82 |
83 | # FUNCTIONS #
84 |
85 | foo () -> True
86 | suma (a,b) -> a+b
87 | foo (a,b) -> "function"
88 | suma (4,5) -> 9
89 |
90 | resta (a,b) -> (c,d) :: c:a-b
91 | d:(a-b)**2
92 |
93 | suma (a,b) -> (c,d) ::
94 | c:a+b
95 | a:a+15
96 | b:5
97 |
98 |
99 | # WHILE #
100 |
101 | while a<56 ::
102 | a:a+1
103 | b:True
104 |
105 | while a<100 ::
106 | if a > 50 then print ("hola") else suma(a,1)
107 | lambda a :: a+1
108 | function (a,b)-> (c,d) ::
109 | c:a+b
110 | d:a-b
111 |
112 | a:0
113 | while a b ::
153 | if a<2 then
154 | b:1
155 | else b: fib(a-1)+ fib(a-2)
156 |
157 |
158 | # QUICKSORT ALGORTIHM #
159 |
160 | quicksort (lista) -> sort_list ::
161 | less : []
162 | eq : []
163 | big : []
164 | if len(lista)>1 then
165 | pivot: lista.0
166 | while (i pivot then add(big,lista.i)
170 | sort_list : quicksort(less) + eq + quicksort(big)
171 | else sort_list : lista
172 |
--------------------------------------------------------------------------------
/tutorials/2_control_flow.md:
--------------------------------------------------------------------------------
1 | # Control Flow
2 |
3 | > In computer science, control flow (or flow of control) is the order in which individual statements, instructions or function calls of an imperative program are executed or evaluated. The emphasis on explicit control flow distinguishes an imperative programming language from a declarative programming language.
4 |
5 | In Squanchy, there are **If-then-(else)** statements and **while** statements, based on Pacal, Haskell and Python. Soon we will have **for** and **Case** and switch statements.
6 |
7 |
8 | ## If/Then/Else
9 |
10 | Based on Pascal and Haskell, the syntax for `if` statement is:
11 |
12 | ```haskell
13 | if then else
14 | ```
15 | The condition or expression doesn't have to be enclosed in parentheses, and `else` is optional.
16 |
17 | Haskell:
18 |
19 | ```haskell
20 | describeLetter :: Char -> String
21 | describeLetter c =
22 | if c >= 'a' && c <= 'z'
23 | then "Lower case"
24 | else if c >= 'A' && c <= 'Z'
25 | then "Upper case"
26 | else "Not an ASCII letter"
27 | ```
28 |
29 | Pascal:
30 |
31 | ```pascal
32 | if a > 0 then
33 | writeln("yes")
34 | else
35 | writeln("no");
36 |
37 | ```
38 |
39 | In Squanchy there are many ways ...
40 |
41 | * Simple **if-then** statement:
42 |
43 | ```pascal
44 | if b<5 and c>10 then d:45
45 | ```
46 |
47 | * Simple **if-then-else** statement:
48 |
49 | ```pascal
50 | if a<=50 then d : "hi!" else d: "bye"
51 | ```
52 |
53 | * **Multi-line** if-then-else statement. In this case you have to take care of `INDENTATION`, but we are very permissive:
54 |
55 | ```haskell
56 | if a<=50
57 | then d : "hi!"
58 | else d: "bye"
59 |
60 | if a<=50
61 | then d : "hi!"
62 | else d: "bye"
63 |
64 |
65 | if a<=50
66 | then
67 | a:a+1
68 | b:b+1
69 | print(a+b)
70 | else
71 | print ("hi!")
72 | ```
73 |
74 | * For **else if**, follow an else with another if statement. Here is an example:
75 |
76 | ```haskell
77 | if a<=50
78 | then
79 | a:a+1
80 | b:b+1
81 | print(a+b)
82 | else if a>10 then print ("hi!")
83 | else print ("bye")
84 | ```
85 |
86 | ## While
87 |
88 | `while` is the basic loop operator. The syntax is:
89 |
90 | ```python
91 | while ::
92 | ```
93 |
94 | As in if statement, the condition or expression doesn't have to be enclosed in parentheses. Simple while loop examples are below:
95 |
96 | ```haskell
97 | while a<56 ::
98 | a:a+1
99 | b:True
100 |
101 | while a<100 ::
102 | if a > 50 then print ("hola") else suma(a,1)
103 | lambda a :: a+1
104 | function (a,b)-> (c,d) ::
105 | c:a+b
106 | d:a-b
107 |
108 | a:0
109 | while a](3_functions.md)
117 |
118 |
119 |
--------------------------------------------------------------------------------
/visualiser.py:
--------------------------------------------------------------------------------
1 | #-------------------------------------------------------------------------------
2 | # Copyright (C) 2018 Gabriel Rodriguez Canal
3 | # Copyright (C) 2018 Marcos V. Conde
4 | #
5 | # This program is free software: you can redistribute it and/or modify
6 | # it under the terms of the GNU General Public License as published by
7 | # the Free Software Foundation, either version 3 of the License, or
8 | # (at your option) any later version.
9 | #
10 | # This program is distributed in the hope that it will be useful,
11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | # GNU General Public License for more details.
14 | #
15 | # You should have received a copy of the GNU General Public License
16 | # along with this program. If not, see .
17 | #-------------------------------------------------------------------------------
18 |
19 | import pydot
20 | import matplotlib.pyplot as plt
21 | import matplotlib.image as mpimg
22 |
23 |
24 | def visualise(tree):
25 |
26 | graph = pydot.Dot(graph_type = 'graph')
27 |
28 | open = [(tree, 0)]
29 | closed = []
30 | nodeCounter = 0
31 | filterLabel = lambda x: x.value if x.id == 'Const' or x.id == 'Name' else x.id
32 |
33 | def nodeColour(id):
34 | if id is 'Const':
35 | return 'green'
36 | elif id is 'Name':
37 | return 'yellow'
38 | elif id is "Module":
39 | return "grey"
40 | else:
41 | return 'cyan'
42 |
43 | while len(open) is not 0:
44 | parent = open[0]
45 | children_ = list(filter(lambda x: x is not None, [parent[0].first, parent[0].second, parent[0].third]))
46 |
47 | children = []
48 | for i in range(len(children_)):
49 | if isinstance(children_[i], (list,)):
50 | children = children_[:i] + children_[i]
51 | else:
52 | children.append(children_[i])
53 |
54 | parentNode = pydot.Node(parent[1], label = filterLabel(parent[0]), style = "filled", fillcolor = nodeColour(parent[0].id))
55 | nodeCounter += 1
56 |
57 | children = list(zip(children, range(nodeCounter, nodeCounter + len(children))))
58 | nodeCounter += len(children)
59 |
60 |
61 | childrenNodes = [pydot.Node(c[1], label = filterLabel(c[0]), style = "filled", fillcolor = nodeColour(c[0].id)) for c in children]
62 |
63 | graph.add_node(parentNode)
64 | [graph.add_node(c) for c in childrenNodes]
65 | [graph.add_edge(pydot.Edge(parentNode, c)) for c in map(lambda x: x[1], children)]
66 |
67 | closed.append(open[0])
68 | open = children + open[1:]
69 |
70 | formato = "svg"
71 | filename = 'draft_tree.%s' % formato
72 | graph.write(filename,format=formato)
73 |
74 | formato = "png"
75 | filename = 'draft_tree.%s' % formato
76 |
77 | graph.write(filename,format=formato)
78 | img = mpimg.imread(filename)
79 | imgplot = plt.imshow(img)
80 | plt.axis("off")
81 | plt.show()
82 |
83 |
84 |
85 |
--------------------------------------------------------------------------------
/codegen.py:
--------------------------------------------------------------------------------
1 | #-------------------------------------------------------------------------------
2 | # Copyright (C) 2018
3 | #
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 | #
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU General Public License for more details.
13 | #
14 | # You should have received a copy of the GNU General Public License
15 | # along with this program. If not, see .
16 | #
17 | # !!! See for more information:
18 | # https://blog.usejournal.com/writing-your-own-programming-language-and-compiler-with-python-a468970ae6df
19 | #-------------------------------------------------------------------------------
20 |
21 |
22 |
23 | from llvmlite import ir, binding
24 | from myeval import Eval
25 |
26 |
27 | class CodeGen():
28 | def __init__(self):
29 | self.binding = binding
30 | self.binding.initialize()
31 | self.binding.initialize_native_target()
32 | self.binding.initialize_native_asmprinter()
33 | self._config_llvm()
34 | self._create_execution_engine()
35 | self._declare_print_function()
36 |
37 | def _config_llvm(self):
38 | # Config LLVM
39 | self.module = ir.Module(name=__file__)
40 | self.module.triple = self.binding.get_default_triple()
41 | func_type = ir.FunctionType(ir.VoidType(), [], False)
42 | base_func = ir.Function(self.module, func_type, name="main")
43 | block = base_func.append_basic_block(name="entry")
44 | self.builder = ir.IRBuilder(block)
45 |
46 | def _declare_print_function(self):
47 | # Declare Printf function
48 | voidptr_ty = ir.IntType(8).as_pointer()
49 | printf_ty = ir.FunctionType(ir.IntType(32), [voidptr_ty], var_arg=True)
50 | printf = ir.Function(self.module, printf_ty, name="printf")
51 | self.printf = printf
52 |
53 | def _create_execution_engine(self):
54 | """
55 | Create an ExecutionEngine suitable for JIT code generation on
56 | the host CPU. The engine is reusable for an arbitrary number of
57 | modules.
58 | """
59 | target = self.binding.Target.from_default_triple()
60 | target_machine = target.create_target_machine()
61 | # And an execution engine with an empty backing module
62 | backing_mod = binding.parse_assembly("")
63 | engine = binding.create_mcjit_compiler(backing_mod, target_machine)
64 | self.engine = engine
65 |
66 | def _compile_ir(self):
67 | """
68 | Compile the LLVM IR string with the given engine.
69 | The compiled module object is returned.
70 | """
71 | # Create a LLVM module object from the IR
72 | self.builder.ret_void()
73 | llvm_ir = str(self.module)
74 | mod = self.binding.parse_assembly(llvm_ir)
75 | mod.verify()
76 | # Now add the module and make sure it is ready for execution
77 | self.engine.add_module(mod)
78 | self.engine.finalize_object()
79 | self.engine.run_static_constructors()
80 | return mod
81 |
82 | def create_ir(self):
83 | self._compile_ir()
84 |
85 | def save_ir(self, filename):
86 | with open(filename, 'w') as output_file:
87 | output_file.write(str(self.module))
88 |
--------------------------------------------------------------------------------
/lexer.py:
--------------------------------------------------------------------------------
1 | #-------------------------------------------------------------------------------
2 | # Copyright (C) 2018 Gabriel Rodriguez Canal
3 | # Copyright (C) 2018 Marcos V. Conde
4 | #
5 | # This program is free software: you can redistribute it and/or modify
6 | # it under the terms of the GNU General Public License as published by
7 | # the Free Software Foundation, either version 3 of the License, or
8 | # (at your option) any later version.
9 | #
10 | # This program is distributed in the hope that it will be useful,
11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | # GNU General Public License for more details.
14 | #
15 | # You should have received a copy of the GNU General Public License
16 | # along with this program. If not, see .
17 | #
18 | # Based on:
19 | # https://gist.github.com/eliben/5797351
20 | #-------------------------------------------------------------------------------
21 |
22 |
23 | import sys
24 | import re
25 | import os
26 | import time
27 | from statistics import mean
28 |
29 |
30 | # REGEX. Regular expressions.
31 |
32 | rules = (
33 | ('stmt', r'\\n\\t|\\n|\\t'),
34 | ('other',r'\s+|;'),
35 | ('Name', r'[a-zA-Z_][\w_]*'),
36 | ('operator', r'(<=|>=|<<|>>|!=|==|:=|<>|::|<-|@|->|\*\*)|[:=+\-*%/\^<>\(\)&!}{\[\]|,.]'),
37 | ('number', r'(:?\d*\.)?\d+'),
38 | ('string', r':?\"+[\w\s\W]+?\"'),
39 | ('cmt',r':?#+[\w\s\W]+?#'))
40 |
41 | regex = re.compile('|'.join(
42 | "(?P<%s>%s)" % t for t in rules))
43 |
44 |
45 | class Token():
46 |
47 | def __init__(self, id, value, pos):
48 | self.id = id
49 | self.value = value
50 | self.pos = pos # error handling
51 |
52 | def __repr__(self):
53 | return "(%s, %s)" % (self.id, self.value)
54 |
55 |
56 | class TokenError(Exception):
57 | pass
58 |
59 | class CmtError(Exception):
60 | pass
61 |
62 | class StrError(Exception):
63 | pass
64 |
65 |
66 |
67 | def lexer (program):
68 |
69 | """Generator. Generate instance(Token).See token_list and debugging comments.
70 | Using generators.
71 | """
72 |
73 | module = Token("Module", "Module", -1)
74 |
75 | yield module
76 | #token_list = [] #only for debugging
77 | #token_list.append(module) #only for debugging
78 |
79 | i = 0
80 |
81 | def error_handling ():
82 | # !!! modificar, añadir linea y corregir la cadena de salida
83 |
84 | pointer = program[:i+1]+"\n"+("-"*(len(program[:i+1])-1))+"^"
85 | print (pointer)
86 |
87 | if program[i] == "#" :
88 | raise CmtError("Comment Error.Start comment at position %d but missing enclose # " % (i+1))
89 | if program[i] == '"' :
90 | raise StrError('String Error.Start string at position %d but missing enclose "' % (i+1))
91 | else:
92 | raise TokenError("Unexpected character at position %d: `%s`" % (i+1, program[i]))
93 |
94 |
95 | for t in regex.finditer(program):
96 |
97 | pos = t.start()
98 |
99 | if pos > i:
100 | error_handling()
101 |
102 | i = t.end()
103 | name = t.lastgroup
104 |
105 | if name == "other" or name == "cmt":
106 | continue
107 | else:
108 | id = "%s" % name
109 | token = Token(id, t.group(0), pos)
110 |
111 | yield token
112 | #token_list.append(token) #only for debugging
113 |
114 | if i < len(program):
115 | error_handling()
116 |
117 | end = Token("(end)", "(end)", pos+1)
118 |
119 | yield end
120 | #token_list.append(end) #only for debugging
121 | return token_list #only for debugging
122 |
123 |
124 | def console ():
125 |
126 | """Interactive console for testing. Must change lexer's code, see debugging comments.
127 | -- commands:
128 | exit
129 | clear
130 | """
131 |
132 | try:
133 | while True:
134 |
135 | expr = input (">> ")
136 |
137 | if expr == "exit": exit()
138 | if expr == "clear":
139 | os.system('clear')
140 | console()
141 | print (lexer(expr))
142 |
143 | except SyntaxError:
144 | print ("ERROR")
145 | console()
146 |
147 |
148 | if "--console" in sys.argv:
149 |
150 | print ("Squanchy PL Lexer Test")
151 | print ("v1.0\n")
152 | console()
153 |
154 |
155 | if "--test" in sys.argv:
156 |
157 | """Benchmark. SQY Lexer vs Python's tokenize module.
158 | Same code written in SQY and Python:
159 | """
160 | maxSize = 200000
161 | difSize = 2000
162 | iterations = int(maxSize / difSize)
163 |
164 | program0 = '+1+1+1+1+1'
165 |
166 | measureSQY = []
167 | measurePY = []
168 | program = program0
169 | for i in range(iterations):
170 | measureSQY.append([])
171 | measurePY.append([])
172 |
173 | progfile = open("code_py.txt","w")
174 | progfile.write(program)
175 | for j in range(1000):
176 | #Squanchy
177 | start = time.time()
178 | print (lexer(program)) # real result with: print(lexer(program))
179 | #lexer(program)
180 | end = time.time()
181 | measureSQY[i].append(end-start)
182 |
183 | #Python
184 | start = time.time()
185 | os.system("python -m tokenize code_py.txt")
186 | end = time.time()
187 | measurePY[i].append(float(end-start))
188 |
189 |
190 | program = program0 * (i+1)
191 |
192 | sqy_time = list(map(lambda x: mean(x), measureSQY))
193 | py_time = list(map(lambda x: mean(x), measurePY))
194 |
195 | # compare times
196 | print ("sqy time >>",sqy_time)
197 | print ("py time >>",py_time)
198 | print ("how better? =", list(map(lambda x,y: float(x/y), py_time, sqy_time)),"times")
199 | exit()
200 |
--------------------------------------------------------------------------------
/ir_code.md:
--------------------------------------------------------------------------------
1 |
2 | ## Code
3 |
4 | **test.sqy**
5 |
6 | ```
7 | # CODE GENERATION EXAMPLE IN SQUANCHY#
8 | # ------------------------------------------------#
9 |
10 | print (1, " hola mundo en Squanchy")
11 |
12 | 425+5266
13 |
14 | 2636-5263+5
15 |
16 | +1*53-4262
17 |
18 | a:5
19 | b:c:d:10
20 |
21 | print ("a = ",a," b = ",b," c= ",c," d= ",d)
22 |
23 | print(a+b-c*d)
24 | print ("b+c = c+d ",b+c = c+d)
25 | print ("a+b < c+d ",a+b < c+d)
26 | print ("a+b > c+d ",a+b > c+d)
27 |
28 | print (400/5+20-15/3)
29 | print (253 and 253)
30 | print (10 or 16)
31 |
32 | # some functions #
33 |
34 | suma (a,b) -> a+b
35 |
36 | resta (a,b) -> a-b
37 |
38 | operation (a,b,c) -> a-b*c
39 |
40 | ```
41 |
42 |
43 | ### AST
44 |
45 | ```
46 |
47 | Module [
48 |
49 | CallFunc(Name (print),[[Const (1), Const (" hola mundo en Squanchy")]])
50 |
51 | Add(Const (425),Const (5266))
52 |
53 | Add(Sub(Const (2636),Const (5263)),Const (5))
54 |
55 | Sub(Mul(UnaryAdd(Const (1)),Const (53)),Const (4262))
56 |
57 | Assign(Name (a),Const (5))
58 |
59 | Assign(Name (b),Assign(Name (c),Assign(Name (d),Const (10))))
60 |
61 | CallFunc(Name (print),[[Const ("a = "), Name (a), Const (" b = "), Name (b), Const (" c= "), Name (c), Const (" d= "), Name (d)]])
62 |
63 | CallFunc(Name (print),[[Sub(Add(Name (a),Name (b)),Mul(Name (c),Name (d)))]])
64 |
65 | CallFunc(Name (print),[[Const ("b+c = c+d "), =(Add(Name (b),Name (c)),Add(Name (c),Name (d)))]])
66 |
67 | CallFunc(Name (print),[[Const ("a+b < c+d "), <(Add(Name (a),Name (b)),Add(Name (c),Name (d)))]])
68 |
69 | CallFunc(Name (print),[[Const ("a+b > c+d "), >(Add(Name (a),Name (b)),Add(Name (c),Name (d)))]])
70 |
71 | CallFunc(Name (print),[[Sub(Add(Div(Const (400),Const (5)),Const (20)),Div(Const (15),Const (3)))]])
72 |
73 | CallFunc(Name (print),[[And(Const (253),Const (253))]])
74 |
75 | CallFunc(Name (print),[[Or(Const (10),Const (16))]])
76 |
77 | Function(Name (suma),[[Name (a), Name (b)], [Add(Name (a),Name (b))]])
78 |
79 | Function(Name (resta),[[Name (a), Name (b)], [Sub(Name (a),Name (b))]])
80 |
81 | Function(Name (operation),[[Name (a), Name (b), Name (c)], [Sub(Name (a),Mul(Name (b),Name (c)))]])
82 | ]
83 |
84 | ```
85 | ### Scope
86 |
87 | ```
88 | {"a": 5, "d": 10, "c": 10, "b": 10}
89 | ```
90 |
91 |
92 |
93 | ### LLVM-IR
94 |
95 | **output.ll**
96 |
97 | ```
98 | ; ModuleID = "..."
99 | target triple = "x86_64-unknown-linux-gnu"
100 | target datalayout = ""
101 |
102 | define void @"main"()
103 | {
104 | entry:
105 | %".2" = alloca [27 x i8]
106 | store [27 x i8] c"%i hola mundo en Squanchy\0a\00", [27 x i8]* %".2"
107 | %".4" = bitcast [27 x i8]* %".2" to i8*
108 | %".5" = call i32 (i8*, ...) @"printf"(i8* %".4", i32 1)
109 | %".6" = add i32 425, 5266
110 | %".7" = sub i32 2636, 5263
111 | %".8" = add i32 %".7", 5
112 | %".9" = add i32 0, 1
113 | %".10" = mul i32 %".9", 53
114 | %".11" = sub i32 %".10", 4262
115 | %".12" = alloca i32
116 | store i32 5, i32* %".12"
117 | %".14" = alloca i32
118 | store i32 10, i32* %".14"
119 | %".16" = alloca i32
120 | store i32 10, i32* %".16"
121 | %".18" = alloca i32
122 | store i32 10, i32* %".18"
123 | %".20" = alloca [27 x i8]
124 | store [27 x i8] c"a = %i b = %i c= %i d= %i\0a\00", [27 x i8]* %".20"
125 | %".22" = bitcast [27 x i8]* %".20" to i8*
126 | %".23" = call i32 (i8*, ...) @"printf"(i8* %".22", i32 5, i32 10, i32 10, i32 10)
127 | %".24" = add i32 5, 10
128 | %".25" = mul i32 10, 10
129 | %".26" = sub i32 %".24", %".25"
130 | %".27" = alloca [4 x i8]
131 | store [4 x i8] c"%i\0a\00", [4 x i8]* %".27"
132 | %".29" = bitcast [4 x i8]* %".27" to i8*
133 | %".30" = call i32 (i8*, ...) @"printf"(i8* %".29", i32 %".26")
134 | %".31" = add i32 10, 10
135 | %".32" = add i32 10, 10
136 | %".33" = icmp eq i32 %".31", %".32"
137 | %".34" = alloca [14 x i8]
138 | store [14 x i8] c"b+c = c+d %i\0a\00", [14 x i8]* %".34"
139 | %".36" = bitcast [14 x i8]* %".34" to i8*
140 | %".37" = call i32 (i8*, ...) @"printf"(i8* %".36", i1 %".33")
141 | %".38" = add i32 5, 10
142 | %".39" = add i32 10, 10
143 | %".40" = icmp slt i32 %".38", %".39"
144 | %".41" = alloca [14 x i8]
145 | store [14 x i8] c"a+b < c+d %i\0a\00", [14 x i8]* %".41"
146 | %".43" = bitcast [14 x i8]* %".41" to i8*
147 | %".44" = call i32 (i8*, ...) @"printf"(i8* %".43", i1 %".40")
148 | %".45" = add i32 5, 10
149 | %".46" = add i32 10, 10
150 | %".47" = icmp sgt i32 %".45", %".46"
151 | %".48" = alloca [14 x i8]
152 | store [14 x i8] c"a+b > c+d %i\0a\00", [14 x i8]* %".48"
153 | %".50" = bitcast [14 x i8]* %".48" to i8*
154 | %".51" = call i32 (i8*, ...) @"printf"(i8* %".50", i1 %".47")
155 | %".52" = sdiv i32 400, 5
156 | %".53" = add i32 %".52", 20
157 | %".54" = sdiv i32 15, 3
158 | %".55" = sub i32 %".53", %".54"
159 | %".56" = alloca [4 x i8]
160 | store [4 x i8] c"%i\0a\00", [4 x i8]* %".56"
161 | %".58" = bitcast [4 x i8]* %".56" to i8*
162 | %".59" = call i32 (i8*, ...) @"printf"(i8* %".58", i32 %".55")
163 | %".60" = and i32 253, 253
164 | %".61" = alloca [4 x i8]
165 | store [4 x i8] c"%i\0a\00", [4 x i8]* %".61"
166 | %".63" = bitcast [4 x i8]* %".61" to i8*
167 | %".64" = call i32 (i8*, ...) @"printf"(i8* %".63", i32 %".60")
168 | %".65" = or i32 10, 16
169 | %".66" = alloca [4 x i8]
170 | store [4 x i8] c"%i\0a\00", [4 x i8]* %".66"
171 | %".68" = bitcast [4 x i8]* %".66" to i8*
172 | %".69" = call i32 (i8*, ...) @"printf"(i8* %".68", i32 %".65")
173 | ret void
174 | }
175 |
176 | declare i32 @"printf"(i8* %".1", ...)
177 |
178 | define i32 @"suma"(i32 %"a", i32 %"b")
179 | {
180 | suma_entry:
181 | %".4" = add i32 5, 10
182 | ret i32 %".4"
183 | }
184 |
185 | define i32 @"resta"(i32 %"a", i32 %"b")
186 | {
187 | resta_entry:
188 | %".4" = sub i32 5, 10
189 | ret i32 %".4"
190 | }
191 |
192 | define i32 @"operation"(i32 %"a", i32 %"b", i32 %"c")
193 | {
194 | operation_entry:
195 | %".5" = mul i32 10, 10
196 | %".6" = sub i32 5, %".5"
197 | ret i32 %".6"
198 | }
199 |
200 | ```
201 |
202 |
203 | Obtenemos **output.ll** del módulo *main.py*, para ejecutar el código basta con escribir los siguientes comandos:
204 |
205 | ```
206 | llc -filetype=obj output.ll
207 | clang output.o -o output
208 | ./output
209 | ```
210 |
--------------------------------------------------------------------------------
/tutorials/1_basic.md:
--------------------------------------------------------------------------------
1 | # Basic Concepts
2 |
3 | The tutorials for most programming languages start with a hello world program,so
4 |
5 | ```
6 | print ("hello world")
7 | ```
8 |
9 | Coming soon:
10 |
11 | ```
12 | print "hello world"
13 | ```
14 |
15 | That's it. Just save that as a normal text file with the extension `.sqy` and run it.
16 |
17 |
18 | ## Primitive Types
19 |
20 | __Int__ is the same as an int in C. It can hold positive and negative whole numbers. The other two primitive data types are Double and List.
21 |
22 | __Double__ is the same as a C Double.
23 |
24 | __List__ is the same as a Python or Haskell list.
25 |
26 | __Bool__ can only be `1` or `0` like C, so in fact is __Int__. We have keywords `True` and `False`.
27 |
28 | __String__ isn't really a primitive data type, it is a __List__ of letters, numbers or other characters of any length, as in Haskell.
29 |
30 |
31 | ## Operators
32 |
33 | In general, operators in Squanchy work the same as in any other language. It has all the ones you would expect with sensible order of operations. The following are the only major differences between operators in Squanchy and Python:
34 | * The assignment operator is `:` instead of `=`.
35 | * The equality operator is `=` instead of `==`.
36 | * The are no semicolons.
37 |
38 | Samples:
39 |
40 | ```python
41 | not a and b
42 | +1 -(-1-5/2)*2**2+(10%2)*3
43 | x * 64 = x << 6
44 | ```
45 |
46 | To sum up:
47 | * Arithmetic Operators: `+ - * / ** %`
48 | * Comparison Operators: `= != < > <= >=`
49 | * Assignment Operators: `:`
50 | * Logical Operators: ` and or not << >>`
51 |
52 | Coming soon:
53 | * Membership Operators `in notin`
54 | * Identity Operators: `is notis`
55 | * Assignment Operators: `+= -=`
56 |
57 |
58 | ## Variables
59 |
60 | A __variable__ is a place you can store a value, string, list, function (as in javascript) ...types are deduced implicitly. To create, change and use a variable, simply do the following:
61 |
62 | ```
63 | myVarName: 78
64 | myVarName: "hello"
65 | myList: [1,2,3,4,5.6,"hi!",23]
66 | myTuple : (a,b,c)
67 | ```
68 |
69 | Javascript
70 |
71 | ```javascript
72 | var foo = function(a,b){ return a+b; }
73 | ```
74 | Squanchy
75 | ```
76 | foo : suma (a,b) -> a+b
77 | ```
78 |
79 | `myVarName` can be any series of letters, digits and underscores, as long as it doesn't start with a number.
80 |
81 |
82 | ## Lists
83 |
84 | Based on Haskell.The square brackets delimit the list, and individual elements are separated by commas. There isn't type restrictions, but elements can't be expressions, must be literals from any primitive type. Elements can be accesed with the `.` operator. Here is an example:
85 |
86 | In Haskell:
87 |
88 | ```haskell
89 | let numbers = [1,2,3,4]
90 | let truths = [True, False, False]
91 | let strings = ["here", "are", "some", "strings"]
92 | ```
93 |
94 | Squanchy:
95 |
96 | ```
97 | numbers : [1,2,3,4]
98 | truths : [True,False,False]
99 | strings : ["here","are","some","strings"]
100 |
101 | list : [1,2,3,4,5,"hello"]
102 |
103 | list_of_list : [1,2,3,[1,2,3]]
104 |
105 | mylist : [12,45463,1.56,"hello",
106 | 45,35,57]
107 |
108 | print (mylist.0)
109 | print (mylist.3)
110 |
111 | multiline_list : [
112 | a,b,c,
113 | d,e,f,
114 | 1,2,3,
115 | "hi!",5.76,True
116 | ]
117 |
118 | ```
119 | The output of this will be
120 | ```
121 | > 12
122 | > "hello"
123 | ```
124 |
125 | ## Tuples
126 |
127 | Based on haskell. To construct one you simple combine several expressions with commas. Elements can be accesed with the `.` operator as __List__. Here is an example:
128 |
129 | From [Haskell](https://en.wikibooks.org/wiki/Haskell/Lists_and_tuples).
130 | > Tuples have a fixed number of elements (immutable); you can't cons to a tuple. Therefore, it makes sense to use tuples when you know in advance how many values are to be stored. For example, we might want a type for storing 2D coordinates of a point. We know exactly how many values we need for each point (two – the x and y coordinates), so tuples are applicable.
131 |
132 | > The elements of a tuple do not need to be all of the same type. For instance, in a phonebook application we might want to handle the entries by crunching three values into one: the name, phone number, and the number of times we made calls. In such a case the three values won't have the same type, since the name and the phone number are strings, but contact counter will be a number, so lists wouldn't work.
133 |
134 | ``` haskell
135 | (True, 1)
136 | ("Hello world", False)
137 | (4, 5, "Six", True, 'b')
138 | ```
139 |
140 | Squanchy
141 | ```
142 | my_Tuple: ("Hello world", False)
143 | my_tuple : (1,"hello",5.6)
144 | print (myTuple.3)
145 | print (myTuple.1)
146 | ```
147 | The output of this will be
148 | ```
149 | > 5.6
150 | > 1
151 | ```
152 |
153 | Tuples within tuples (and other combinations):
154 | ```
155 | ((2,3), True)
156 | ((2,3), [2,3])
157 | [(1,2), (3,4), (5,6)]
158 | ```
159 |
160 |
161 | ## Global and Constants
162 |
163 | Squanchy handles local (function) and global (module) namespaces.
164 |
165 | A __global__ variable can be accessible (read & write) from any Scope/Namespace. A global variable is not the same as a variable allocated on global scope . You can declare global variables by explicitly using the `global` keyword as follows: `global var_name` . Here is an example of a simple use:
166 |
167 | ```
168 | global a
169 | a : 5
170 | inc (x) -> a:x+a
171 | inc (5)
172 | print (a)
173 | ```
174 | The output of this will be
175 | ```
176 | > 10
177 | ```
178 |
179 | A global variable can only store literals (primitive types).
180 |
181 |
182 | A __constant__ is a value that is determined at compile time,is changeless and accessible from any Scope-Namespace. Constants are created with the constants assignment operator `:=`. Here is an example of a simple use and declaration:
183 |
184 | ```
185 | a := 5
186 | print (a)
187 | inc (x) -> x+a
188 | print (inc (5))
189 |
190 | a: 10
191 |
192 | ```
193 | The output of this will be
194 | ```
195 | > 5
196 | > 10
197 | > error
198 | ```
199 |
200 | In this case `a` is no longer a `Name`, now is `Const`.
201 |
202 |
203 | ## Comments
204 |
205 | Comment is a programmer-readable explanation or annotation in the source code of a computer program that the compiler doesn't look at. In Squanchy, single-line comments and multi-line comments are exactly the same, both start with `#` and end with `#`.
206 |
207 |
208 | ```
209 | # simple comment #
210 |
211 | # multiline
212 | comment #
213 | ```
214 |
215 | [index](index.md) | [next: Control Flow ->](2_control_flow.md)
216 |
--------------------------------------------------------------------------------
/myeval.py:
--------------------------------------------------------------------------------
1 | #-------------------------------------------------------------------------------
2 | # Copyright (C) 2018 Marcos V. Conde
3 | #
4 | # This program is free software: you can redistribute it and/or modify
5 | # it under the terms of the GNU General Public License as published by
6 | # the Free Software Foundation, either version 3 of the License, or
7 | # (at your option) any later version.
8 | #
9 | # This program is distributed in the hope that it will be useful,
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | # GNU General Public License for more details.
13 | #
14 | # You should have received a copy of the GNU General Public License
15 | # along with this program. If not, see .
16 | #-------------------------------------------------------------------------------
17 |
18 |
19 | import llvmlite.ir as ir
20 | import llvmlite.binding as llvm
21 | from ctypes import CFUNCTYPE
22 | import os
23 | import json
24 |
25 |
26 | i32_ty = ir.IntType(32)
27 |
28 | def Eval(node, scope,builder = None,module= None,printf= None):
29 |
30 | """
31 | Main Evaluation function. If builder recieved (builder != None)
32 | then generates code on that IRBuilder.
33 | If builder == None, return the "simple" value of the expression .
34 | For example:
35 | - 4+5 -> Eval(Add (Cont 4, Cont 5))
36 | -> return 9
37 | -> return builder.add(4,5), wich generates
38 | """
39 |
40 | codegen = {
41 |
42 | "+": lambda first,second: builder.add(first, second),
43 | "-": lambda first,second: builder.sub(first, second),
44 | "not": lambda first,second: builder.not_(first),
45 | "*": lambda first,second: builder.mul(first, second),
46 | "/": lambda first,second: builder.sdiv(first, second),
47 | "and": lambda first,second: builder.and_(first, second),
48 | "or": lambda first,second: builder.or_(first, second),
49 | "!=": lambda first,second: builder.icmp_signed("!=",first,second),
50 | "=": lambda first,second: builder.icmp_signed("==",first,second),
51 | "<": lambda first,second: builder.icmp_signed("<",first,second),
52 | ">": lambda first,second: builder.icmp_signed(">",first,second),
53 | "<=": lambda first,second: builder.icmp_signed("<=",first,second),
54 | ">=": lambda first,second: builder.icmp_signed(">=",first,second)
55 |
56 | }
57 |
58 | operations = {
59 |
60 | "+": lambda first,second: first+second,
61 | "-": lambda first,second: first-second,
62 | "not": lambda first,second: not first,
63 | "*": lambda first,second: first*second,
64 | "/": lambda first,second: int(first/second),
65 | "%": lambda first,second: first%second,
66 | "**": lambda first,second: first**second,
67 | "and": lambda first,second: first and second,
68 | "or": lambda first,second: first or second,
69 | "!=": lambda first,second: first != second,
70 | "=": lambda first,second: first == second,
71 | "<": lambda first,second: first": lambda first,second: first>second,
73 | "<=": lambda first,second: first<=second,
74 | ">=": lambda first,second: first >= second,
75 | }
76 |
77 |
78 | #print (scope)
79 | #print ("node = ",node,node.first,node.second)
80 |
81 | if node.id == "Name":
82 | try:
83 | if type (scope.names[node.value]) == list:
84 | return scope.names[node.value]
85 | else:
86 | if builder == None:
87 | try:
88 | return int(scope.names[node.value])
89 | except:
90 | return scope.names[node.value]
91 | else:
92 | try:
93 | return i32_ty(int(scope.names[node.value]))
94 | except:
95 | return scope.names[node.value]
96 | except:
97 | raise NotDefined('Name "%s" is not defined' % node.value)
98 |
99 |
100 | if node.id == "Const":
101 | if builder == None:
102 | try:
103 | return int(node.value)
104 | except:
105 | return node.value
106 | else:
107 | try:
108 | return i32_ty(int(node.value))
109 | except:
110 | return node.value.strip('"')
111 |
112 | if node.name == "Assign":
113 |
114 | if builder == None:
115 | return Eval(node.second,scope)
116 | else:
117 | val = Eval(node.second,scope,builder,module)
118 | ptr = builder.alloca(val.type)
119 | builder.store(val, ptr)
120 | return val
121 |
122 | if node.name == "List":
123 | return str([x.value for x in node.first])
124 |
125 | if node.name == "Tuple":
126 | return str([x.value for x in node.first])
127 |
128 | # OPERATOR
129 | if node.arity == 2:
130 |
131 | first= Eval(node.first,scope,builder,module)
132 | second= Eval(node.second,scope,builder,module)
133 | op = node.id
134 |
135 | if builder == None:
136 | return operations[op](first,second)
137 | else:
138 | return codegen[op](first,second)
139 |
140 | elif node.arity == 1:
141 |
142 | second= Eval(node.first,scope,builder,module)
143 | first = i32_ty(int(0))
144 | op = node.id
145 |
146 | if builder == None:
147 | return operations[op](first,second)
148 | else:
149 | return codegen[op](first,second)
150 |
151 | else:
152 | # is a statement
153 | # only print call considered.
154 |
155 | if builder !=None:
156 |
157 | func_name = node.first.value
158 | args = [x.value for x in node.second[0]]
159 |
160 |
161 | if func_name == "print":
162 | eval_print(node,scope,builder,module,printf)
163 |
164 | # basic functions
165 | elif node.id== "Function":
166 | #print (node)
167 | #print (func_name)
168 | #print (args)
169 |
170 | # de momento solo tipo int
171 | type_arg = [i32_ty for i in args]
172 |
173 | func_ty = ir.FunctionType(ir.IntType(32), type_arg)
174 | func = ir.Function(module, func_ty, name=func_name)
175 |
176 | for i in range(len(args)):
177 | func.args[i].name = args[i]
178 |
179 | name_block = func_name+"_entry"
180 | fn_block = func.append_basic_block(name_block)
181 | func_builder = ir.IRBuilder(fn_block)
182 |
183 | tmp = Eval(node.second[1][0],scope,func_builder,module)
184 | ret = func_builder.ret(tmp)
185 |
186 | #print(module)
187 | elif node.id == "CallFunc":
188 | return "CALL"
189 | else:
190 | pass
191 | else:
192 | return "PROC"
193 |
194 |
195 | class NotDefined(Exception):
196 | pass
197 |
198 |
199 |
200 | def eval_print(node,scope,builder,module,printf):
201 |
202 | # print ("hola mundo",5) -> CallFunc(Name (print),[[Const ("hola mundo"), Const (5)]])
203 |
204 | end = "\n\0"
205 | arg = ""
206 | values = []
207 |
208 | args = node.second[0] # list of arguments to print
209 | for a in args:
210 |
211 | arg_value = Eval(a,scope,builder,module)
212 | if type(arg_value) == str:
213 | arg += arg_value
214 | else:
215 | arg += "%i"
216 | values.append (arg_value)
217 |
218 | arg+=end
219 |
220 | voidptr_ty = ir.IntType(8).as_pointer()
221 | c_str_val = ir.Constant(ir.ArrayType(ir.IntType(8), len(arg)),
222 | bytearray(arg.encode("utf8")))
223 |
224 | c_str = builder.alloca(c_str_val.type)
225 | builder.store(c_str_val, c_str)
226 | fmt_arg = builder.bitcast(c_str, voidptr_ty)
227 |
228 | # Call Print Function
229 | in_ = [fmt_arg]
230 | in_ += values
231 | builder.call(printf, in_)
232 |
--------------------------------------------------------------------------------
/example.md:
--------------------------------------------------------------------------------
1 |
2 | ## Code
3 |
4 |
5 | ```
6 | # CODE EXAMPLE IN SQUANCHY#
7 | # ------------------------------------------------#
8 |
9 |
10 | # prueba de comentario
11 | multilnea#
12 |
13 |
14 | # OPERATORS #
15 |
16 | a+b*c**2-(-1/2)
17 |
18 | x:5+6
19 | x:y:z:8
20 |
21 | not a or b and c
22 |
23 | pi
24 |
25 | tuple : (a,b,c)
26 |
27 | True and False
28 |
29 | (a<<2)+1
30 |
31 |
32 | # LISTS #
33 |
34 | numbers : [1,2,3,4]
35 | truths : [True,False,False]
36 | strings : ["here","are","some","strings"]
37 |
38 | list : [1,2,3,4,5,"hello"]
39 | mylist : [12,45463,1.56,"hello",
40 | 45,35,57]
41 |
42 | list_of_list : [1,2,3,[1,2,3]]
43 |
44 |
45 | multiline_list : [
46 | a,b,c,
47 | d,e,f,
48 | 1,2,3,
49 | "hi!",5.76,True
50 | ]
51 |
52 |
53 | # TUPLES #
54 |
55 | my_Tuple: ("Hello world", False)
56 | my_tuple : (1,"hello",5.6)
57 | ((2,3), True)
58 | ((2,3), [2,3])
59 | [(1,2), (3,4), (5,6)]
60 |
61 |
62 | mylist.1
63 | my_tuple.3
64 |
65 | # GLOBAL #
66 |
67 | global u
68 | global v
69 |
70 |
71 | # CONSTANTS #
72 |
73 | a := 5
74 | b := True
75 | c := "constant"
76 |
77 |
78 | # LAMBDA #
79 |
80 | add : lambda a b :: a+b
81 | lambda r :: r**2*pi
82 |
83 |
84 | # FUNCTIONS #
85 |
86 | foo () -> True
87 | suma (a,b) -> a+b
88 | foo (a,b) -> "function"
89 | suma (4,5) -> 9
90 |
91 | resta (a,b) -> (c,d) :: c:a-b
92 | d:(a-b)**2
93 |
94 | suma (a,b) -> (c,d) ::
95 | c:a+b
96 | a:a+15
97 | b:5
98 |
99 |
100 | # WHILE #
101 |
102 | while a<56 ::
103 | a:a+1
104 | b:True
105 |
106 | while a<100 ::
107 | if a > 50 then print ("hola") else suma(a,1)
108 | lambda a :: a+1
109 | function (a,b)-> (c,d) ::
110 | c:a+b
111 | d:a-b
112 |
113 | a:0
114 | while a b ::
154 | if a<2 then
155 | b:1
156 | else b: fib(a-1)+ fib(a-2)
157 |
158 |
159 | # QUICKSORT ALGORTIHM #
160 |
161 | quicksort (lista) -> sort_list ::
162 | less : []
163 | eq : []
164 | big : []
165 | if len(lista)>1 then
166 | pivot: lista.0
167 | while (i pivot then add(big,lista.i)
171 | sort_list : quicksort(less) + eq + quicksort(big)
172 | else sort_list : lista
173 |
174 | ```
175 |
176 |
177 | ### AST
178 |
179 | ```
180 | Module [
181 |
182 | Sub(Add(Name (a),Mul(Name (b),Power(Name (c),Const (2)))),Div(UnarySub(Const (1)),Const (2)))
183 |
184 | Assign(Name (x),Add(Const (5),Const (6)))
185 |
186 | Assign(Name (x),Assign(Name (y),Assign(Name (z),Const (8))))
187 |
188 | Or(Not(Name (a)),And(Name (b),Name (c)))
189 |
190 | Const (3.141592653589793)
191 |
192 | Assign(Name (tuple),Tuple([Name (a), Name (b), Name (c)]))
193 |
194 | And(Const (1),Const (0))
195 |
196 | Add(LeftShift(Name (a),Const (2)),Const (1))
197 |
198 | Assign(Name (numbers),List([Const (1), Const (2), Const (3), Const (4)]))
199 |
200 | Assign(Name (truths),List([Const (1), Const (0), Const (0)]))
201 |
202 | Assign(Name (strings),List([Const ("here"), Const ("are"), Const ("some"), Const ("strings")]))
203 |
204 | Assign(Name (list),List([Const (1), Const (2), Const (3), Const (4), Const (5), Const ("hello")]))
205 |
206 | Assign(Name (mylist),List([Const (12), Const (45463), Const (1.56), Const ("hello"), Const (45), Const (35), Const (57)]))
207 |
208 | Assign(Name (list_of_list),List([Const (1), Const (2), Const (3), List([Const (1), Const (2), Const (3)])]))
209 |
210 | Assign(Name (multiline_list),List([Name (a), Name (b), Name (c), Name (d), Name (e), Name (f), Const (1), Const (2), Const (3), Const ("hi!"), Const (5.76), Const (1)]))
211 |
212 | Assign(Name (my_Tuple),Tuple([Const ("Hello world"), Const (0)]))
213 |
214 | Assign(Name (my_tuple),Tuple([Const (1), Const ("hello"), Const (5.6)]))
215 |
216 | Tuple([Tuple([Const (2), Const (3)]), Const (1)])
217 |
218 | Tuple([Tuple([Const (2), Const (3)]), List([Const (2), Const (3)])])
219 |
220 | List([Tuple([Const (1), Const (2)]), Tuple([Const (3), Const (4)]), Tuple([Const (5), Const (6)])])
221 |
222 | Access(Name (mylist),Const (1))
223 |
224 | Access(Name (my_tuple),Const (3))
225 |
226 | global(Name (u))
227 |
228 | global(Name (v))
229 |
230 | Let(Name (a),Const (5))
231 |
232 | Let(Name (b),Const (1))
233 |
234 | Let(Name (c),Const ("constant"))
235 |
236 | Assign(Name (add),Lambda([Name (a), Name (b)],Add(Name (a),Name (b))))
237 |
238 | Lambda([Name (r)],Mul(Power(Name (r),Const (2)),Const (3.141592653589793)))
239 |
240 | Function(Name (foo),[[], [Const (1)]])
241 |
242 | Function(Name (suma),[[Name (a), Name (b)], [Add(Name (a),Name (b))]])
243 |
244 | Function(Name (foo),[[Name (a), Name (b)], [Const ("function")]])
245 |
246 | Function(Name (suma),[[Const (4), Const (5)], [Const (9)]])
247 |
248 | Function(Name (resta),[[Name (a), Name (b)], [Tuple([Name (c), Name (d)])]],[Assign(Name (c),Sub(Name (a),Name (b))), Assign(Name (d),Power(Sub(Name (a),Name (b)),Const (2)))])
249 |
250 | Function(Name (suma),[[Name (a), Name (b)], [Tuple([Name (c), Name (d)])]],[Assign(Name (c),Add(Name (a),Name (b))), Assign(Name (a),Add(Name (a),Const (15))), Assign(Name (b),Const (5))])
251 |
252 | while(<(Name (a),Const (56)),[Assign(Name (a),Add(Name (a),Const (1))), Assign(Name (b),Const (1))])
253 |
254 | while(<(Name (a),Const (100)),[IfExp(>(Name (a),Const (50)),[CallFunc(Name (print),[[Const ("hola")]])],[CallFunc(Name (suma),[[Name (a), Const (1)]]), Lambda([Name (a)],Add(Name (a),Const (1))), Function(Name (function),[[Name (a), Name (b)], [Tuple([Name (c), Name (d)])]],[Assign(Name (c),Add(Name (a),Name (b))), Assign(Name (d),Sub(Name (a),Name (b)))])])])
255 |
256 | Assign(Name (a),Const (0))
257 |
258 | while(<(Name (a),CallFunc(Name (len),[[Name (lista)]])),[Assign(Access(Name (lista),Name (a)),Name (a)), Assign(Name (a),Add(Name (a),Const (1)))])
259 |
260 | IfExp(Name (a),[Name (b)],[Name (c)])
261 |
262 | IfExp(Name (a),[Name (b), Name (c), Name (d)],[IfExp(Name (a1),[Name (b2)],[Name (c2)])])
263 |
264 | IfExp(<=(Name (a),Const (50)),[Assign(Name (d),Const ("hi!"))],[Assign(Name (d),Const ("bye"))])
265 |
266 | IfExp(<=(Name (a),Const (50)),[Assign(Name (d),Const ("hi!"))],[Assign(Name (d),Const ("bye"))])
267 |
268 | while(Name (a),[while(Name (b),[while(Name (c),[while(Name (d),[while(Name (e),[while(Name (f),[while(Name (g),[Name (pass)])])])])])])])
269 |
270 | Function(Name (fib),[[Name (a)], [Name (b)]],[IfExp(<(Name (a),Const (2)),[Assign(Name (b),Const (1))],[Assign(Name (b),Add(CallFunc(Name (fib),[[Sub(Name (a),Const (1))]]),CallFunc(Name (fib),[[Sub(Name (a),Const (2))]])))])])
271 |
272 | Function(Name (quicksort),[[Name (lista)], [Name (sort_list)]],[Assign(Name (less),List()), Assign(Name (eq),List()), Assign(Name (big),List()), IfExp(>(CallFunc(Name (len),[[Name (lista)]]),Const (1)),[Assign(Name (pivot),Access(Name (lista),Const (0))), while(<(Name (i),CallFunc(Name (len),[[Name (lista)]])),[IfExp(<(Access(Name (lista),Name (i)),Name (pivot)),[CallFunc(Name (add),[[Name (less), Access(Name (lista),Name (i))]]), IfExp(=(Access(Name (lista),Name (i)),Name (pivot)),[CallFunc(Name (add),[[Name (eq), Access(Name (lista),Name (i))]]), IfExp(>(Access(Name (lista),Name (i)),Name (pivot)),[CallFunc(Name (add),[[Name (big), Access(Name (lista),Name (i))]]), Assign(Name (sort_list),Add(Add(CallFunc(Name (quicksort),[[Name (less)]]),Name (eq)),CallFunc(Name (quicksort),[[Name (big)]])))],[Assign(Name (sort_list),Name (lista))])])])])])])
273 | ]
274 |
275 |
276 | ```
277 |
278 | ### Scope
279 |
280 | ```
281 | {"x": 8, "z": 8, "y": 8, "pi": 3.141592653589793, "tuple": "['a', 'b', 'c']", "True": 1, "False": 0, "numbers": "['1', '2', '3', '4']", "truths": "[1, 0, 0]", "strings": "['\"here\"', '\"are\"', '\"some\"', '\"strings\"']", "list": "['1', '2', '3', '4', '5', '\"hello\"']", "mylist": "['12', '45463', '1.56', '\"hello\"', '45', '35', '57']", "list_of_list": "['1', '2', '3', '[']", "multiline_list": "['a', 'b', 'c', 'd', 'e', 'f', '1', '2', '3', '\"hi!\"', '5.76', 1]", "my_Tuple": "['\"Hello world\"', 0]", "my_tuple": "['1', '\"hello\"', '5.6']", "a": 0, "b": "PROCPROC", "c": 22, "add": "PROC", "d": "\"bye\"", ".": 0, "less": "[]", "eq": "[]", "big": "[]", "pivot": "PROC", "sort_list": "test-mode"}
282 |
283 | ```
284 |
285 | En el Scope los valores: PROC y test-mode corresponden a la evaluación de ciertas funciones, listas ... que todavía no esta implementada.
286 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | [](https://github.com/Jesucrist0/Squanchy-PL/issues)
2 | [](https://www.gnu.org/licenses/gpl-3.0)
3 | 
4 | [](https://github.com/Jesucrist0/Squanchy-PL)
5 | [](https://www.amazon.es/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882/ref=pd_lpo_sbs_14_t_0?_encoding=UTF8&psc=1&refRID=HYBK4ZCEKQREQCC461CC)
6 |
7 |
8 | # Squanchy Programming Language
9 | **_Bastard son of Python and Haskell, and failed Scratch_**
10 |
11 |
12 |
13 | ## Important
14 |
15 | - [code.sqy](code.sqy) Example of code written in Squancy. Ejemplo de código escrito en Squanchy.
16 | - [example.md](example.md) Parser test example, see the AST. Ejemplo para comprobar el parser y ver el AST generado.
17 | - [ir_code.md](ir_code.md) Comprobar la generacin de código intermedio LLVM y compilación.
18 |
19 |
20 | ## About
21 | Squanchy is a brand new, easy to learn, general purpose, multi-paradigm, compiled programming language created by:
22 |
23 | * **Marcos V** [mv-lab](https://github.com/mv-lab)
24 |
25 | Student at University of Valladolid.
26 | Alumno de la Universidad de Valladolid.
27 |
28 | Work on the language began on September, 2018.
29 |
30 | Related to the courses: Algorithms and computing, Formal Grammars and Languages.
31 | Asignaturas relacionadas: Algoritmos y Computación, Gramáticas y Lenguajes formales.
32 |
33 | The language is written from scratch (it includes an integrated lexer, parser, code generator etc).
34 |
35 | **Why?**
36 |
37 | - Python is lit, that's all, arguably one of the best programming languages ever.
38 | - I wrote the same code in Haskell and Java. Now you see how concise, clean, and perfect is Haskell code:
39 |
40 |
41 |
42 | ```java
43 | final int LIMIT = 50;
44 | int[] a = new int[LIMIT];
45 | int[] b = new int [LIMIT-5];
46 | for (int i=0; i< LIMIT; i++){
47 | a[i] = (i+1)*2;
48 | if (i >= 5) b(i-5)= [i];
49 | }
50 | ```
51 | ```haskell
52 | let a = [2,4...100]
53 | let b = drop 5 a
54 |
55 | ```
56 |
57 | So I tried to put together Python and Haskell (or at least the main features from both) in Squanchy.
58 |
59 |
60 | #### Contact [](mailto:marcosventura.conde@alumnos.uva.es)
61 |
62 | #### This project is licensed under the GNU General Public License v3.0 - see the [LICENSE.md](LICENSE.md) file for details
63 |
64 | #### Built With
65 |
66 | [](https://www.python.org/download/releases/3.0/)
67 |
68 |
69 |
70 |
71 | ---
72 |
73 | ## Getting Started
74 |
75 | Here is Fibonacci demo program written in Haskell and Squanchy. You can see more code example in [example](example.md).
76 |
77 | ```haskell
78 |
79 | fib x
80 | | x < 2 = 1
81 | | otherwise = fib (x - 1) + fib (x - 2)
82 |
83 |
84 | fib 1 = 1
85 | fib 2 = 2
86 | fib x = fib (x - 1) + fib (x - 2)
87 |
88 | ```
89 | Squanchy:
90 |
91 | ```haskell
92 | fib (x) -> y ::
93 | if x<2 then y:1 else y: fib(x-1)+fib(x-2)
94 |
95 |
96 | fib (1) -> 1
97 | fib (2) -> 2
98 | fib(x) -> fib(x-1) + fib(x-2)
99 |
100 | ```
101 |
102 | __If you want to program in Squanchy now, see the [tutorials](tutorials/index.md) for how to get started.__
103 |
104 |
105 |
106 | ## Current State
107 | The features that are currently implemented are as follows:
108 |
109 | * Primitive data types `List`,`String`, `Int` and `Double`
110 | * Operators (`+`,`-`, `*`,`/`,`**`, `%`, `:`, `=`, `>`, `<=`, `and`,`or`, etc.)
111 | * Flow control (if/the/else, while loop)
112 | * Constants and global variables
113 | * Lists, Tuples and access
114 | * Functions
115 | * Lambda
116 |
117 | The following features are coming soon:
118 |
119 | * Flow control (ternary ?, for)
120 | * Data structs
121 | * Dictionaries
122 | * array (like numpy)
123 | * more default functions
124 | * fixed visualisation module
125 | * ...
126 |
127 |
128 | ## Contributing
129 |
130 | ```prolog
131 | This is an open source project.
132 | ```
133 | 
134 |
135 | * Gabriel Rodríguez Canal [@gabrielrodcanal](https://github.com/gabrielrodcanal)
136 |
137 | You want to contribute?
138 | Please do! The source code is hosted at GitHub. If you want something, open an issue or a pull request.
139 | If you need want to contribute but don't know where to start, take a look at:
140 |
141 | - [Step by step guide to make your first contribution](https://codeburst.io/a-step-by-step-guide-to-making-your-first-github-contribution-5302260a2940)
142 | - [Github guideline for repository contributors](https://help.github.com/articles/setting-guidelines-for-repository-contributors/)
143 |
144 | This is the main [documentation](documentation.pdf) of the project, only Spanish version (for the moment). Also
145 | you can checkout down below all my sources in Bibliography
146 |
147 | Before doing anything, see [Code of Conduct](CODE_OF_CONDUCT.md)
148 |
149 | **Contributing Code**
150 |
151 | 1. Fork it!
152 | 2. Create your feature branch: `git checkout -b my-new-feature`
153 | 3. Commit your changes: `git commit -am 'Add some feature'`
154 | 4. Push to the branch: `git push origin my-new-feature`
155 | 5. Submit a pull request
156 |
157 | Check this out if you don't know how to start:
158 |
159 |
160 | ## Aims and objectives
161 |
162 | - [x] Make it work
163 | - [x] Basic code generation
164 | - [ ] Beautiful and Clean Code + documentation !!
165 | - [ ] Add data structures and arrays
166 | - [ ] IDLE for Squanchy: something easy and minimalist, just write & run like Jupyter.
167 | - [ ] Work on the code optimization
168 | - [ ] Update tutorials, documentation ...
169 | - [ ] a ton of things more
170 |
171 |
172 | ---
173 |
174 | ## Bibliography
175 |
176 | ### General
177 |
178 | - [The Python Language Reference](https://docs.python.org/3.3/reference/index.html#reference-index)
179 | - [Compilers: Principles, Techniques, and Tools 2ed](https://en.wikipedia.org/wiki/Compilers:_Principles,_Techniques,_and_Tools)
180 | - [Let’s Build A Simple Interpreter](https://ruslanspivak.com/lsbasi-part9/)
181 | - [Parsing Techniques: A Practical Guide](https://www.researchgate.net/publication/233437139_Parsing_Techniques_A_Practical_Guide)
182 |
183 | ### Lexer
184 |
185 | - [Using Regular Expressions for Lexical Analysis](http://effbot.org/zone/xml-scanner.htm)
186 | - [Write your own lexer](http://pygments.org/docs/lexerdevelopment/)
187 | - [Eiben Github ](https://gist.github.com/eliben/5797351)
188 | - [Parsing In Python: Tools And Libraries](https://tomassetti.me/parsing-in-python/)
189 |
190 | ### Parser
191 |
192 | Pratt Parser implementation.
193 |
194 | - [Top down operator precedence by Vaughan R. Pratt](https://web.archive.org/web/20151223215421/http://hall.org.ua/halls/wizzard/pdf/Vaughan.Pratt.TDOP.pdf)
195 | - [A New Approach of Complier Design in Context of Lexical
196 | Analyzer and Parser Generation for NextGen Languages](https://pdfs.semanticscholar.org/f449/3fc2ac5491ff626d1aa6e3142aac87d0960f.pdf)
197 | - [Top down operator precedence](https://tdop.github.io/)
198 | - [ Simple Top-Down Parsing in Python](http://effbot.org/zone/simple-top-down-parsing.htm)
199 | - [Top Down Operator Precedence by Douglas Crockford](http://crockford.com/javascript/tdop/tdop.html)
200 | - [Pratt Parsers: Expression Parsing Made Easy](http://journal.stuffwithstuff.com/2011/03/19/pratt-parsers-expression-parsing-made-easy/)
201 | - [Pratt Parsing and Precedence Climbing Are the Same Algorithm](https://www.oilshell.org/blog/2016/11/01.html)
202 | - [Review of Pratt/TDOP Parsing Tutorials](https://www.oilshell.org/blog/2016/11/02.html)
203 | - [A Pratt Parser implementation in Python](https://github.com/percolate/pratt-parser)
204 | - [A Guide to Parsing: Algorithms and Terminology](https://tomassetti.me/guide-parsing-algorithms-terminology/)
205 | - [Parsing text with Python](https://www.vipinajayakumar.com/parsing-text-with-python/)
206 |
207 |
208 | ### Interpreter and Code generation
209 |
210 | - [Compiler Design | Intermediate Code Generation](https://www.geeksforgeeks.org/intermediate-code-generation-in-compiler-design/)
211 | - [Compilers Algorithms](http://www.softpanorama.org/Algorithms/compilers.shtml)
212 | - [Compiler Design - Code Optimization](https://www.tutorialspoint.com/compiler_design/compiler_design_code_optimization.htm)
213 | - [Writing your own programming language and compiler with Python](https://blog.usejournal.com/writing-your-own-programming-language-and-compiler-with-python-a468970ae6df)
214 | - [68 Resources To Help You To Create Programming Languages](https://tomassetti.me/resources-create-programming-languages/)
215 |
--------------------------------------------------------------------------------
/parser.py:
--------------------------------------------------------------------------------
1 | #-------------------------------------------------------------------------------
2 | # Copyright (C) 2018 Gabriel Rodriguez Canal
3 | # Copyright (C) 2018 Marcos V. Conde
4 | #
5 | # This program is free software: you can redistribute it and/or modify
6 | # it under the terms of the GNU General Public License as published by
7 | # the Free Software Foundation, either version 3 of the License, or
8 | # (at your option) any later version.
9 | #
10 | # This program is distributed in the hope that it will be useful,
11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | # GNU General Public License for more details.
14 | #
15 | # You should have received a copy of the GNU General Public License
16 | # along with this program. If not, see .
17 | #-------------------------------------------------------------------------------
18 |
19 |
20 | import sys
21 | import re
22 | import json
23 | import time
24 | import visualiser as visu
25 | from statistics import mean
26 | import os
27 | from myeval import Eval
28 |
29 |
30 | # symbol: constans, operators, ids, keywords
31 | # symbol_table = {symbol : symbol_class}
32 |
33 | token_list = []
34 |
35 | symbol_table = {}
36 |
37 | names_map = {"+":"Add","-":"Sub","*":"Mul","/":"Div",
38 | "**":"Power","%":"Mod","and":"And","or":"Or",
39 | "&":"Bitand","^":"Bitxor",
40 | "<<":"LeftShift",">>":"RightSift","lambda":"Lambda",
41 | "if":"IfExp","[":"List",":":"Assign",".":"Access",":=":"Let","<-":"Data",
42 | "\\t":"TAB","\\n\\t":"INDENT","\\n":"NEWLINE"}
43 |
44 |
45 |
46 | #--------------------------------------------------------------------------------------------
47 | # NAME SPACE | SCOPE
48 |
49 | class Scope:
50 |
51 | """Clase espacio de nombres. Scope
52 | See https://pythonspot.com/scope/
53 | Modeliza un espacio donde las variables son definidas y accesibles,
54 | pudiendo haber variables locales y globales.
55 | """
56 |
57 | def __init__ (self):
58 |
59 | self.names = {}
60 |
61 | def define (self,n):
62 |
63 | """ Define nuevas variables en el espacio .
64 | Transforma el token de un nombre a una variable.
65 | Error si la variable ya esta en el espacio, o si el nombre dado ya esta reservado.
66 | """
67 | t = self.names[n.value]
68 | if t:
69 | raise NameError ("Already defined or reserved %r" % n)
70 |
71 | self.names[n.value] = n
72 | n.reserved = False
73 | name.nud = lambda self: self
74 | n.led = None
75 | n.lbp = 0
76 | n.space = space
77 | return n
78 |
79 | def find (self,name):
80 |
81 | """Encuentra la defincion de , el valor.
82 | Busca en el espacio actual y si no lo encuentra sube niveles,
83 | en ultima instancia devuelve valor en symbol_table si no lo encuentra.
84 | Además comprueba si no esta undefined o es una funcion.
85 | """
86 |
87 | return self.names[name]
88 | """
89 | e = self
90 | while 1:
91 | o = e.names[name]
92 | if o and o.arity != "function":
93 | return e.names[name]
94 |
95 | e = e.parent
96 | if not e:
97 | o = symbol_table[name];
98 | if o.arity != "function": return o
99 | else: return symbol_table["Name"]
100 | """
101 |
102 | def pop (self):
103 |
104 | """Asciende un nivel en la jerárquia del espacio de nombres.
105 | """
106 | scope = self.parent
107 |
108 |
109 | def reserve(self,id,value):
110 |
111 | """Indica que se ha usado o es una palabra reservada
112 | en el espacio actual .
113 | Por ejemplo "if" será reservada y no podrá usarse como nombre de variable o funcion.
114 | Los nombres se reservan localmente solo cuando se usen como palabras reservadas.
115 |
116 | """
117 |
118 | try:
119 | t = self.names[id]
120 | if t:
121 | self.names[id] = value # update value
122 | #raise NameError ("Already defined")
123 |
124 | except KeyError:
125 | self.names[id] = value
126 | #name.reserved = True
127 |
128 |
129 | def __repr__(self):
130 | return json.dumps(self.names)
131 |
132 |
133 | def new_space ():
134 | s = space
135 | space = Scope()
136 | space.parent = s
137 | return space;
138 |
139 | SCOPE = Scope()
140 |
141 |
142 | #--------------------------------------------------------------------------------------------
143 |
144 |
145 | def symbol(id, bp=0):
146 |
147 | """Creates a new class for token (if necessary)
148 |
149 | Param:
150 | id -- token's id or symbol
151 | bp -- binding power
152 |
153 | Return:
154 | Protoclass -- Symbol Class. Sample: token's id = "+"
155 | then return the symbol's <+> class, called SymClass_+
156 |
157 | """
158 |
159 | try:
160 | Protoclass = symbol_table[id]
161 | except KeyError:
162 |
163 | class Protoclass:
164 |
165 | """Prototype Class model for grammar symbols.
166 | Default nud and led methods.
167 | Default attributes: lbp, id, value, arity ...
168 | """
169 |
170 | # Class attributes
171 |
172 | lbp = bp
173 | value = id
174 |
175 |
176 | def __init__ (self):
177 |
178 | self.first = self.second = self.third = None
179 | self.id = id
180 | self.arity = None
181 | self.reserved = False
182 | try : self.name = names_map[self.id]
183 | except KeyError: self.name= self.id
184 |
185 |
186 | def nud (self):
187 | """Default nud method.
188 | Check prefix
189 | """
190 | print ("problema, NUD no definido ", self.id)
191 | if self.name == "INDENT":
192 | raise IndentationError ('Incorrect use of TABS.')
193 |
194 |
195 | def led (self,left):
196 |
197 | """Default led method.
198 | Check infix and infix_r.
199 | """
200 | print ("problema, LED no definido ", self.id)
201 | raise SyntaxError("Syntax error (%r)." % self.id)
202 |
203 |
204 | def __repr__(self):
205 |
206 | out = [self.first, self.second, self.third]
207 | out = map(str, filter(None, out))
208 |
209 | if self.arity == 1:
210 | return self.name +"("+ "".join(out) + ")"
211 |
212 | elif self.id == "Name" or self.id == "Const":
213 | return "%s (%s)" % (self.id, self.value)
214 |
215 | return self.name + "("+ ",".join(out) + ")"
216 |
217 | Protoclass.__name__ = "SymClass_" + id
218 | symbol_table[id] = Protoclass
219 |
220 | else:
221 | Protoclass.lbp = max(bp, Protoclass.lbp)
222 |
223 | return Protoclass
224 |
225 |
226 |
227 | def advance (id=None):
228 |
229 | """Genera la instancia el token siguiente según su correspondiente clase.
230 | Permite comparar el id del siguiente con un id pasado por párametro.
231 |
232 | Párametros:
233 | id -- id del token que vamos a instanciar (next token).
234 | Si id = None simplemente se instanciará el siguiente token.
235 | Si id tiene un valor, se compmrobará antes de instanciar.
236 | """
237 |
238 | global token
239 | if id and token.id != id:
240 | raise SyntaxError("Expected %r" % id)
241 |
242 | if token.id == "(end)": pass
243 | else:
244 | token = next()
245 |
246 |
247 | def ignore (id=None):
248 |
249 | """ MOD of advance function. Ignores token , advance until sees token different than
250 | """
251 |
252 | global token
253 | while token.id == id:
254 | token = next()
255 | if token.id == "(end)": pass
256 |
257 |
258 | def add_method(symbol_class):
259 |
260 | """Decorator. Add as method, if exists.
261 | """
262 | assert symbol_class in symbol_table.values()
263 | def new_method(fn):
264 | setattr(symbol_class, fn.__name__, fn) # (class, function name, value = funcion)
265 | return new_method
266 |
267 |
268 |
269 | def prefix(id, bp):
270 |
271 | """
272 | Prefix expressions.
273 | Arity 1.
274 | Examples: +,-, not => UnaryAdd, UnaryMinus, Not
275 | """
276 |
277 | names = {"+":"UnaryAdd", "-":"UnarySub","not":"Not"}
278 | def nud(self):
279 | self.first = parse(bp)
280 | self.name = names[self.id]
281 | self.solve = self.first
282 | self.arity = 1
283 | return self
284 | symbol(id).nud=nud
285 |
286 |
287 | def infix(id,bp):
288 |
289 | def led(self, left):
290 | self.first = left
291 | self.second = parse(bp)
292 | self.arity = 2
293 | return self
294 | symbol(id,bp).led=led
295 |
296 |
297 |
298 | # special infix case: right associative
299 | def infix_r(id,bp):
300 | def led(self, left):
301 | self.first = left
302 | self.second = parse(bp-1) # solves right associative
303 | self.arity = 2
304 | return self
305 | symbol(id,bp).led=led
306 |
307 |
308 |
309 | # Fill Symbol Table
310 | # To understand bp and operator precedence:
311 | # See https://docs.python.org/3/reference/expressions.html | 6.16. Operator precedence
312 |
313 | symbol("Const")
314 | symbol("Name")
315 | symbol("(end)")
316 |
317 |
318 | # OPERATORS
319 |
320 | prefix("+", 130); prefix("-", 130); prefix("not", 50)
321 |
322 | infix("+",110); infix("-",110)
323 | infix("*",120); infix("/",120)
324 | infix("%",120); infix("not", 60)
325 | infix("<<",100); infix(">>",90)
326 | infix("<",60); infix("<=",60)
327 | infix(">",60); infix(">=",60)
328 | infix("!=",60); infix("=",60) # "different" and "equal" symbols
329 |
330 | infix_r("**",140); infix_r("or",20); infix_r("and",40)
331 |
332 |
333 | # Constants
334 | symbol("global",1000)
335 |
336 | # Lists
337 | symbol("[", 150);symbol("]")
338 | symbol(".",150) #index
339 |
340 | # Parentheses and Tuples
341 | symbol("(", 150);symbol(")");symbol(",")
342 |
343 | # Statement
344 | symbol("::"); symbol("->"); infix("<-",10)
345 | symbol(":",10); symbol(":=",15)
346 | symbol("|")
347 | symbol("lambda",20)
348 | symbol("while",20)
349 | symbol("if", 20); symbol("then",15); symbol("else")
350 |
351 | symbol(")"); symbol(",")
352 | symbol("}");symbol("{"); symbol(",");symbol(":");symbol(";")
353 | symbol("\\n\\t"); symbol("\\n") ; symbol("\\t")
354 |
355 | symbol("Module")
356 |
357 |
358 |
359 | #--------------------------------------------------------------------------------------------
360 | # Add NUD and LED methods to each symbol using decorator (if necessary)
361 | # Remember each symbol has his own class with default atributtes and methods created above
362 | # so we may have to change them.
363 |
364 |
365 | symbol("Const").nud = lambda self: self
366 |
367 |
368 | #symbol("Const").solve = lambda self: self.value
369 |
370 | """
371 | @add_method(symbol("Name"))
372 | def nud (self):
373 |
374 | #print (SCOPE)
375 | if self.value not in SCOPE.names:
376 | return self
377 | else:
378 | # FunCall
379 | self.name = self.id = "FunCall"
380 | self.first = token
381 | print ("arg:",self.first)
382 | advance()
383 | return self
384 | """
385 | symbol("Name").nud = lambda self: self # !!!
386 |
387 |
388 | #--------------------------------------------------------------------------------------------
389 |
390 | def constant(id,value):
391 | @add_method(symbol(id))
392 | def nud(self):
393 | self.id = self.name = "Const"
394 | self.value = value
395 | SCOPE.reserve(id,value)
396 | return self
397 |
398 | constant("null",None)
399 | constant("True",1)
400 | constant("False",0)
401 | constant("pi", 3.141592653589793)
402 |
403 |
404 |
405 | # global Name -> accessible from any SCOPE
406 | @add_method(symbol("global"))
407 | def nud (self):
408 | self.first = token # var
409 | advance("Name")
410 | constant(self.first.value,None)
411 | return self
412 |
413 |
414 | def assigment (self,left):
415 | #print ("Estoy en assigment")
416 | self.first = left;
417 | self.second = parse(self.lbp-1)
418 | self.arity = 2
419 | try:
420 | SCOPE.reserve(self.first.value,Eval(self.second,SCOPE))
421 | except:
422 | SCOPE.reserve(self.first.value,"test-mode")
423 | #SCOPE.reserve(self.first.value,"test-mode")
424 | #print ("son:",self.first.value,Eval(self.second))
425 | #print (SCOPE)
426 | return self
427 |
428 | symbol(":").led = assigment
429 | symbol(":=").led = assigment
430 |
431 |
432 | # a <- { elem1: int, elem2: Dub, elem3:string} => is structure a
433 | # a <- [] => a is array
434 | # a: {..} => a is dic
435 |
436 | #--------------------------------------------------------------------------------------------
437 | # LISTS
438 | # expression_list ::= [expressions...]
439 |
440 | @add_method(symbol("["))
441 | def nud(self):
442 | self.first = []
443 | if token.id != "]":
444 | while 1:
445 | ignore(NEWLINE);ignore(INDENT);ignore(TAB)
446 | #assert token.id == "Const"
447 | #self.first.append(token)
448 | #advance()
449 | #if token.id == "]":break
450 | self.first.append(parse()) # check parse is an expression
451 |
452 | ignore(NEWLINE);ignore(INDENT);ignore(TAB)
453 | if token.id != ",": break
454 | advance(",")
455 |
456 | advance("]")
457 | self.arity = 1
458 | self.name = "List"
459 | return self
460 |
461 |
462 | #--------------------------------------------------------------------------------------------
463 | # TUPLES
464 | # expression_tuple ::= (expressions...)
465 |
466 | @add_method(symbol("("))
467 | def nud(self):
468 | self.first = []
469 | if token.id != ")":
470 | while 1:
471 | if token.id == ")":
472 | break
473 | #self.first.append(token)
474 | self.first.append(parse())
475 | if token.id != ",":
476 | break
477 | advance(",")
478 | advance(")")
479 |
480 | if len(self.first) > 1:
481 | self.name = "Tuple"
482 | return self # tuple
483 |
484 | elif len(self.first) == 1:
485 | return self.first[0] # expr
486 | else:
487 | raise SyntaxError ("Bad Tuple")
488 |
489 |
490 | #--------------------------------------------------------------------------------------------
491 | # Item access. INDEX
492 |
493 | # expression_access ::= (List|Tuple).Const
494 | # !!! list,tuples,dic & types
495 |
496 | @add_method(symbol("."))
497 | def led(self, left):
498 | if token.id != "Const":
499 | SyntaxError("Expected numeric index.")
500 | self.first = left
501 | self.second = token
502 | advance()
503 | return self
504 |
505 |
506 |
507 | #--------------------------------------------------------------------------------------------
508 | # LAMBDA FUNCTION
509 |
510 | # lambda [parameter_list]:: expression
511 | # lambda [parameter_list]:: expression_nocond
512 |
513 |
514 | @add_method(symbol("lambda"))
515 | def nud(self):
516 | self.first = [] # arg
517 | if token.id != "::":
518 | parameter_list(self.first)
519 | if len(self.first )==0:
520 | raise SyntaxError ("Bad lambda, no arguments")
521 | advance("::")
522 | self.second = parse() # tiene que ser una expression
523 | return self
524 |
525 |
526 | def parameter_list(list):
527 | while 1:
528 | if token.id != "Name":
529 | SyntaxError("Expected a parameter Name.")
530 | list.append(token)
531 | advance()
532 | if token.id == "::": break
533 |
534 |
535 | #--------------------------------------------------------------------------------------------
536 | # STATEMENTS | BLOCK
537 |
538 |
539 | """
540 | program : Module
541 | Module : statement|block
542 | block : statement_list | statement [end_block] statement_list
543 | statement_list : statement|statement [end_stmt] statement_list
544 | statement : simple_statement| assign_statement | empty
545 | empty:
546 |
547 | """
548 |
549 | TAB = "\\t"
550 | INDENT = "\\n\\t"
551 | NEWLINE = "\\n"
552 | SEMICOLON = ";"
553 | end_stmt = [INDENT,"(end)",SEMICOLON]
554 |
555 |
556 | def statement (end_block):
557 |
558 | """Parsea un statement hasta llegar a o
559 | """
560 |
561 |
562 | if (token.id in ["while","if","else","then"]):
563 | t = token
564 | advance()
565 | return t.nud()
566 |
567 | statement = parse()
568 |
569 | if token.id in end_block:
570 | pass
571 | elif token.id in end_stmt: advance(token.id)
572 | else:
573 | raise SyntaxError ("Expected %r" % end_stmt)
574 |
575 | return statement
576 |
577 |
578 |
579 | def statement_list (end_block=[NEWLINE,"(end)"]):
580 |
581 | """Parsea statements hasta llegar a .
582 | Return:
583 | - statement
584 | - stmt = array of statements
585 | - None si no hay statement
586 | """
587 |
588 | stmt = [] # array of statements
589 |
590 | while 1:
591 |
592 | if token.id in end_block :
593 | break
594 | ignore(INDENT)
595 | ignore(TAB)
596 |
597 | """
598 | for k in range (1,level):
599 | try:
600 | advance(TAB)
601 | except:
602 | raise IndentationError('Expected TAB but found "%s" '% token)
603 | """
604 |
605 | s = statement(end_block) # un solo statement
606 | if s:
607 | stmt.append(s)
608 | ignore(INDENT)
609 |
610 | if len(stmt) == 0: return None
611 | elif len(stmt) == 1: return [stmt[0]] # s
612 | else: return stmt
613 |
614 |
615 | def block (key=None):
616 | t = token
617 | advance(key)
618 | ignore(INDENT)
619 | return t.nud()
620 |
621 |
622 | @add_method(symbol("::"))
623 | def nud (self):
624 | a = statement_list()
625 | return a
626 |
627 |
628 | #--------------------------------------------------------------------------------------------
629 | # FUNCTION CALLS & FUNCTION DECLARATION
630 |
631 | """
632 | FUNCTION_SKELETON =
633 | {name} {args} -> {return} :: {body}
634 | """
635 |
636 |
637 | @add_method(symbol("("))
638 | def led(self,left):
639 |
640 | self.first = left
641 | self.second = []
642 | arg = []
643 | ret = []
644 |
645 | if token.id != ")":
646 | while 1:
647 | if token.id == ")":break
648 | arg.append(parse())
649 | if token.id != ",":break
650 | advance(",")
651 |
652 | advance(")")
653 | self.second.append(arg)
654 |
655 | # sería en el scope de la función no en el general
656 |
657 | """
658 | for i in arg:
659 | name = self.first.value+"_"+i.value
660 | SCOPE.reserve(name,"undefined")
661 | """
662 |
663 | if self.first.value in SCOPE.names:
664 | #funcall
665 | #print (self.first)
666 | self.third = None
667 | self.arity = "2"
668 | self.name = "CallFunc"
669 | self.id = self.name
670 | return self
671 |
672 |
673 | #SCOPE.new (left.value,left.value)
674 | #print (SCOPE)
675 |
676 | try:
677 | advance ("->")
678 | except:
679 | self.third = None
680 | self.arity = "2"
681 | self.name = "CallFunc"
682 | self.id = self.name
683 | return self
684 | #t = token
685 | #advance()
686 |
687 | ret.append(parse())
688 | #ret.append(t.nud())
689 | self.second.append(ret)
690 |
691 | # statement
692 | try :
693 | self.third = block("::")
694 | self.arity = "statement"
695 |
696 | except SyntaxError:
697 | pass
698 |
699 | self.name = "Function"
700 | self.id = self.name
701 |
702 | return self
703 |
704 |
705 | #--------------------------------------------------------------------------------------------
706 | # WHILE statement
707 |
708 | symbol("while").arity = "statement"
709 | symbol("while").name = "While_stmt"
710 |
711 | @add_method(symbol("while"))
712 | def nud (self):
713 |
714 | self.first = parse(20)
715 | self.second = block("::")
716 |
717 | if self.second == None:
718 | raise WhileError ('While Statement Error. No statement found after ::')
719 |
720 | return self
721 |
722 | #--------------------------------------------------------------------------------------------
723 | # IF-THEN-ELSE statement
724 |
725 | symbol("if").arity = "statement"
726 |
727 | @add_method(symbol("then"))
728 | def nud (self):
729 | stm = statement_list(["(end)","else",NEWLINE])
730 | return stm
731 |
732 |
733 | @add_method(symbol("else"))
734 | def nud (self):
735 | a = statement_list()
736 | return a
737 |
738 |
739 | @add_method(symbol("if"))
740 | def nud(self):
741 | self.first = parse(20)
742 | ignore(NEWLINE); ignore(INDENT)
743 |
744 | try :
745 | self.second = block("then")
746 | except:
747 | raise IfError ('Expected "then" but found "%s" '% token)
748 |
749 | if self.second == None :
750 | raise IfError ('IF-THEN Statement Error. No Statement found after "then"')
751 |
752 | ignore(NEWLINE)
753 | if token.id == "else":
754 | self.third = block("else")
755 | if self.third == None :
756 | raise IfError('IF-THEN-ELSE Statement Error. No Statement found after "else"')
757 |
758 | self.arity = "statement"
759 | return self
760 |
761 |
762 | #--------------------------------------------------------------------------------------------
763 | # MODULE/PROGRAM statement
764 |
765 | def module ():
766 | program = []
767 |
768 | ignore (NEWLINE)
769 | if token.id != "(end)":
770 | while 1:
771 | ignore (NEWLINE)
772 | #ignore (INDENT)
773 | ignore (SEMICOLON)
774 | if token.id == "(end)": break
775 | if token.id == NEWLINE: ignore(NEWLINE)
776 | program.append(parse())
777 |
778 | advance("(end)")
779 | return program
780 |
781 |
782 | @add_method(symbol("Module"))
783 | def nud (self):
784 | self.first = module()
785 | return self
786 |
787 |
788 | @add_method(symbol("Module"))
789 | def __repr__ (self):
790 | out = self.first
791 | out = map(str, out)
792 | return "Module [ \n\n\t"+ "\n\n\t".join(out) +"\n]"
793 |
794 |
795 |
796 | #--------------------------------------------------------------------------------------------
797 | # LEXER CALL
798 |
799 | def tokenize(program):
800 |
801 | """
802 | # Genera una instancia 'atom' para la clase asociada al token obtenido mediante tokenize_python
803 | # (tokenize module). Ver symbol_table.
804 | """
805 |
806 | from lexer import lexer
807 |
808 | for token in lexer(program):
809 |
810 | if token.id == "number" or token.id == "string":
811 | Clase_token = symbol_table["Const"]
812 | atom = Clase_token()
813 | atom.value = token.value
814 |
815 | else:
816 |
817 | Clase_token = symbol_table.get(token.value)
818 |
819 | if Clase_token:
820 | atom = Clase_token()
821 |
822 | elif token.id == "Name":
823 |
824 | Clase_token = symbol_table[token.id]
825 | atom = Clase_token()
826 | atom.value = token.value
827 | else:
828 | raise SyntaxError("Unknown operator (%r)" % token.value)
829 |
830 | yield atom
831 |
832 |
833 | #--------------------------------------------------------------------------------------------
834 | # PARSER ENGINE
835 |
836 |
837 | def parse(rbp=0):
838 |
839 | """
840 | Pratt parser implementation.
841 | See "Top Down Operator Precedence" (section 3: Implementation, pág 47)
842 | """
843 |
844 | global token
845 | t = token
846 | advance()
847 | left = t.nud()
848 |
849 | while rbp < token.lbp:
850 | t = token
851 | advance()
852 | left = t.led(left)
853 | return left
854 |
855 |
856 |
857 | def ast(program):
858 |
859 | """Creates AST using Pratt's Parser
860 | """
861 |
862 | global token,next,level
863 |
864 | next = tokenize(program).__next__
865 | token = next()
866 | level = 0
867 | tree = parse()
868 | return tree,SCOPE
869 |
870 |
871 | #--------------------------------------------------------------------------------------------
872 | # ERRORS
873 |
874 | class WhileError(Exception):
875 | pass
876 |
877 | class IfError(Exception):
878 | pass
879 |
880 | class IndentationError(Exception):
881 | pass
882 |
883 | #--------------------------------------------------------------------------------------------
884 | # OPTIONS
885 |
886 |
887 | def console ():
888 |
889 | """Interactive console for testing. Must change lexer's code, see debugging comments.
890 | -- commands:
891 | exit
892 | clear
893 | """
894 |
895 | try:
896 | while True:
897 | expr = input (">> ")
898 | if expr == "exit": exit()
899 | if expr == "clear":
900 | os.system('clear')
901 | console()
902 | print (ast(expr)[0].first[0])
903 |
904 | except Exception as e:
905 | print (e.args[0])
906 | console()
907 |
908 |
909 | if "--terminal" in sys.argv:
910 |
911 | """Interactive terminal for testing
912 | """
913 |
914 | print ("Squanchy PL console test")
915 | print ("v1.1","\n")
916 | console()
917 |
918 |
919 | if "--img" in sys.argv:
920 |
921 | """Test tree visualisation.
922 | """
923 | program = input (">> ")
924 | tree,scope = ast(program)
925 | print (program, "-> ",tree,"\n")
926 | visu.visualise(tree)
927 |
928 |
929 | if "--in" in sys.argv:
930 |
931 | """Test input
932 | """
933 |
934 | f = open("code.sqy")
935 | program = f.read()
936 | f.close()
937 |
938 | program = program.replace("\n","\\n").replace("\t","\\t")
939 |
940 | tree,scope = ast(program)
941 | print ("\n",tree)
942 | print ("\n",scope)
943 |
944 |
945 | if "--benchmark" in sys.argv:
946 | factor = 1
947 | program = '1+1+1+1+1+1+1+1+1'*10000
948 |
949 | measure = []
950 |
951 | for i in range(factor):
952 | measure.append([])
953 | for j in range(1000):
954 | start = time.time()
955 | ast(program)
956 | end = time.time()
957 | measure[i].append(float(end-start))
958 | program = ((program + '+')*10)[:-1]
959 |
960 | print("Time: ", list(map(lambda x: mean(x), measure)))
961 |
962 |
963 |
964 | def main():
965 | pass
966 |
967 |
968 | if __name__ == "__main__":
969 | main()
970 |
971 |
972 |
973 |
974 |
975 |
976 |
977 |
978 |
979 |
980 |
981 |
982 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------