Compare commits
8
Commits
b253eed032
...
0.4.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
badeea9b28 | ||
|
|
a1267c4395 | ||
|
|
55fd3ea716 | ||
|
|
697bafdcee | ||
|
|
28b83f9892 | ||
|
|
194fc8aca6 | ||
|
|
382532e0e1 | ||
|
|
c0eba1ecf0 |
No files matched your search
@@ -0,0 +1,53 @@
|
|||||||
|
# Пример расчета суммы ряда
|
||||||
|
|
||||||
|
Рассмотрим как можно посчитать предел суммы ряда на lyng. Для наивной реализации
|
||||||
|
представим что у нас есть функция рассчитывающая n-й член ряда. Тогда мы можем
|
||||||
|
считать сумму до тех пор, пока отклонение при расчете следующего члена не станет
|
||||||
|
меньше чем заданная погрешность:
|
||||||
|
|
||||||
|
fun сумма_ряда(x, погрешность=0.0001, f) {
|
||||||
|
var сумма = 0
|
||||||
|
for( n in 1..100000) {
|
||||||
|
val следующая_сумма = сумма + f(x, n)
|
||||||
|
if( n > 1 && abs(следующая_сумма - сумма) < погрешность )
|
||||||
|
break следующая_сумма
|
||||||
|
сумма = следующая_сумма
|
||||||
|
}
|
||||||
|
else null
|
||||||
|
}
|
||||||
|
|
||||||
|
Для проверки можно посчитать на хорошо известном ряду Меркатора
|
||||||
|
|
||||||
|
$$ \ln(1+x)=x-{\dfrac {x^{2}}{2}}+{\dfrac {x^{3}}{3}}-\cdots =\sum \limits _{n=0}^{\infty }{\dfrac {(-1)^{n}x^{n+1}}{(n+1)}}=\sum \limits _{n=1}^{\infty }{\dfrac {(-1)^{n-1}x^{n}}{n}} $$
|
||||||
|
|
||||||
|
Который в нашем случае для точки $ x = 1 $ можно записать так:
|
||||||
|
|
||||||
|
val x = сумма_ряда(1) { x, n ->
|
||||||
|
val sign = if( n % 2 == 1 ) 1 else -1
|
||||||
|
sign * pow(x, n) / n
|
||||||
|
}
|
||||||
|
|
||||||
|
Проверим:
|
||||||
|
|
||||||
|
assert( x - ln(2) < 0.001 )
|
||||||
|
|
||||||
|
В нашем примере есть изъян - погрешность вычисляется примитивно: `abs(следующая_сумма - сумма) < погрешность`, что совершенно неверно, если значения малы. Значительно более корректно вычислять погрешность, нормированную на диапазон сравниваемых величин:
|
||||||
|
|
||||||
|
|
||||||
|
fun погрешность(x0, x1) {
|
||||||
|
abs( x1 - x0 ) / (abs( x1 + x0 ) / 2.0)
|
||||||
|
}
|
||||||
|
// относительная погрешность одинакова и в разных диапазонах
|
||||||
|
assertEquals( погрешность(5,6), погрешность(0.005,0.006))
|
||||||
|
|
||||||
|
Теперь мы могли бы написать более корректное сравнение для вещественных
|
||||||
|
|
||||||
|
// расхождение не больше 1% или сколько укажете:
|
||||||
|
fun почти_равны(a,b,epsilon=0.01) {
|
||||||
|
погрешность(a,b) <= epsilon
|
||||||
|
}
|
||||||
|
assert( почти_равны( 0.0005, 0.000501 ) )
|
||||||
|
|
||||||
|
Во многих случаях вычисление $n+1$ члена значительно проще cчитается от предыдущего члена, в нашем случае это можно было бы записать через итератор, что мы вскоре добавим.
|
||||||
|
|
||||||
|
(продолжение следует)
|
||||||
+65
-10
@@ -15,8 +15,7 @@ __Other documents to read__ maybe after this one:
|
|||||||
- [OOP notes](OOP.md)
|
- [OOP notes](OOP.md)
|
||||||
- [math in Lyng](math.md)
|
- [math in Lyng](math.md)
|
||||||
- Some class references: [List], [Real], [Range], [Iterable], [Iterator]
|
- Some class references: [List], [Real], [Range], [Iterable], [Iterator]
|
||||||
- Some samples: [combinatorics](samples/combinatorics.lyng.md)
|
- Some samples: [combinatorics](samples/combinatorics.lyng.md), national vars and loops: [сумма ряда](samples/сумма_ряда.lyng.md). More at [samples folder](samples)
|
||||||
See [samples folder](samples)
|
|
||||||
|
|
||||||
# Expressions
|
# Expressions
|
||||||
|
|
||||||
@@ -555,16 +554,16 @@ Or, more neat:
|
|||||||
|
|
||||||
## while
|
## while
|
||||||
|
|
||||||
Regular pre-condition while loop, as expression, loop returns it's last line result:
|
Regular pre-condition while loop, as expression, loop returns the last expression as everything else:
|
||||||
|
|
||||||
var count = 0
|
var count = 0
|
||||||
while( count < 5 ) {
|
val result = while( count < 5 ) count++
|
||||||
count++
|
result
|
||||||
count * 10
|
>>> 4
|
||||||
}
|
|
||||||
>>> 50
|
|
||||||
|
|
||||||
We can break as usual:
|
Notice it _is 4 because when count became 5, the loop body was not executed!_.
|
||||||
|
|
||||||
|
We can break while as usual:
|
||||||
|
|
||||||
var count = 0
|
var count = 0
|
||||||
while( count < 5 ) {
|
while( count < 5 ) {
|
||||||
@@ -683,6 +682,36 @@ So the returned value, as seen from diagram could be one of:
|
|||||||
- value returned from the `else` clause, of the loop was not broken
|
- value returned from the `else` clause, of the loop was not broken
|
||||||
- value returned from the last execution of loop body, if there was no `break` and no `else` clause.
|
- value returned from the last execution of loop body, if there was no `break` and no `else` clause.
|
||||||
|
|
||||||
|
## do-while loops
|
||||||
|
|
||||||
|
There works exactly as while loops but the body is executed prior to checking the while condition:
|
||||||
|
|
||||||
|
var i = 0
|
||||||
|
do { i++ } while( i < 1 )
|
||||||
|
i
|
||||||
|
>>> 1
|
||||||
|
|
||||||
|
The important feature of the do-while loop is that the condition expression is
|
||||||
|
evaluated on the body scope, e.g., variables, intruduced in the loop body are
|
||||||
|
available in the condition:
|
||||||
|
|
||||||
|
do {
|
||||||
|
var continueLoop = false
|
||||||
|
"OK"
|
||||||
|
} while( continueLoop )
|
||||||
|
>>> "OK"
|
||||||
|
|
||||||
|
This is sometimes convenient when condition is complex and has to be calculated inside the loop body. Notice the value returning by the loop:
|
||||||
|
|
||||||
|
fun readLine() { "done: result" }
|
||||||
|
val result = do {
|
||||||
|
val line = readLine()
|
||||||
|
} while( !line.startsWith("done:") )
|
||||||
|
result.drop(6)
|
||||||
|
>>> "result"
|
||||||
|
|
||||||
|
Suppose readLine() here reads some stream of lines.
|
||||||
|
|
||||||
|
|
||||||
## For loops
|
## For loops
|
||||||
|
|
||||||
@@ -792,7 +821,7 @@ See [Ranges](Range.md) for detailed documentation on it.
|
|||||||
|
|
||||||
// single line comment
|
// single line comment
|
||||||
var result = null // here we will store the result
|
var result = null // here we will store the result
|
||||||
>>> void
|
>>> null
|
||||||
|
|
||||||
# Integral data types
|
# Integral data types
|
||||||
|
|
||||||
@@ -838,10 +867,36 @@ Are the same as in string literals with little difference:
|
|||||||
|
|
||||||
## String details
|
## String details
|
||||||
|
|
||||||
|
Strings are much like Kotlin ones:
|
||||||
|
|
||||||
|
"Hello".length
|
||||||
|
>>> 5
|
||||||
|
And supports growing set of kotlin-borrowed operations, see below, for example:
|
||||||
|
|
||||||
|
assertEquals("Hell", "Hello".dropLast(1))
|
||||||
|
>>> void
|
||||||
|
|
||||||
### String operations
|
### String operations
|
||||||
|
|
||||||
Concatenation is a `+`: `"hello " + name` works as expected. No confusion.
|
Concatenation is a `+`: `"hello " + name` works as expected. No confusion.
|
||||||
|
|
||||||
|
Typical set of String functions includes:
|
||||||
|
|
||||||
|
| fun/prop | description / notes |
|
||||||
|
|------------------|------------------------------------------------------------|
|
||||||
|
| lower() | change case to unicode upper |
|
||||||
|
| upper() | change case to unicode lower |
|
||||||
|
| startsWith(prefix) | true if starts with a prefix |
|
||||||
|
| take(n) | get a new string from up to n first characters |
|
||||||
|
| takeLast(n) | get a new string from up to n last characters |
|
||||||
|
| drop(n) | get a new string dropping n first chars, or empty string |
|
||||||
|
| dropLast(n) | get a new string dropping n last chars, or empty string |
|
||||||
|
| size | size in characters like `length` because String is [Array] |
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
### Literals
|
### Literals
|
||||||
|
|
||||||
String literal could be multiline:
|
String literal could be multiline:
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import org.jetbrains.kotlin.gradle.ExperimentalWasmDsl
|
|||||||
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
|
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
|
||||||
|
|
||||||
group = "net.sergeych"
|
group = "net.sergeych"
|
||||||
version = "0.3.0-SNAPSHOT"
|
version = "0.4.0-SNAPSHOT"
|
||||||
|
|
||||||
buildscript {
|
buildscript {
|
||||||
repositories {
|
repositories {
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ data class ArgsDeclaration(val params: List<Item>, val endTokenType: Token.Type)
|
|||||||
*/
|
*/
|
||||||
suspend fun assignToContext(
|
suspend fun assignToContext(
|
||||||
context: Context,
|
context: Context,
|
||||||
_fromArgs: Arguments = context.args,
|
arguments: Arguments = context.args,
|
||||||
defaultAccessType: AccessType = AccessType.Var,
|
defaultAccessType: AccessType = AccessType.Var,
|
||||||
defaultVisibility: Visibility = Visibility.Public
|
defaultVisibility: Visibility = Visibility.Public
|
||||||
) {
|
) {
|
||||||
@@ -33,17 +33,31 @@ data class ArgsDeclaration(val params: List<Item>, val endTokenType: Token.Type)
|
|||||||
}
|
}
|
||||||
|
|
||||||
// will be used with last lambda arg fix
|
// will be used with last lambda arg fix
|
||||||
val fromArgs = _fromArgs
|
val callArgs: List<Obj>
|
||||||
|
val paramsSize: Int
|
||||||
|
|
||||||
|
if( arguments.tailBlockMode ) {
|
||||||
|
paramsSize = params.size - 1
|
||||||
|
assign(params.last(), arguments.list.last())
|
||||||
|
callArgs = arguments.list.dropLast(1)
|
||||||
|
} else {
|
||||||
|
paramsSize = params.size
|
||||||
|
callArgs = arguments.list
|
||||||
|
}
|
||||||
|
|
||||||
suspend fun processHead(index: Int): Int {
|
suspend fun processHead(index: Int): Int {
|
||||||
var i = index
|
var i = index
|
||||||
while (i != params.size) {
|
while (i != paramsSize) {
|
||||||
val a = params[i]
|
val a = params[i]
|
||||||
if (a.isEllipsis) break
|
if (a.isEllipsis) break
|
||||||
val value = when {
|
val value = when {
|
||||||
i < fromArgs.size -> fromArgs[i]
|
i < callArgs.size -> callArgs[i]
|
||||||
a.defaultValue != null -> a.defaultValue.execute(context)
|
a.defaultValue != null -> a.defaultValue.execute(context)
|
||||||
else -> context.raiseArgumentError("too few arguments for the call")
|
else -> {
|
||||||
|
println("callArgs: ${callArgs.joinToString()}")
|
||||||
|
println("tailBlockMode: ${arguments.tailBlockMode}")
|
||||||
|
context.raiseArgumentError("too few arguments for the call")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
assign(a, value)
|
assign(a, value)
|
||||||
i++
|
i++
|
||||||
@@ -52,14 +66,14 @@ data class ArgsDeclaration(val params: List<Item>, val endTokenType: Token.Type)
|
|||||||
}
|
}
|
||||||
|
|
||||||
suspend fun processTail(index: Int): Int {
|
suspend fun processTail(index: Int): Int {
|
||||||
var i = params.size - 1
|
var i = paramsSize - 1
|
||||||
var j = fromArgs.size - 1
|
var j = callArgs.size - 1
|
||||||
while (i > index) {
|
while (i > index) {
|
||||||
val a = params[i]
|
val a = params[i]
|
||||||
if (a.isEllipsis) break
|
if (a.isEllipsis) break
|
||||||
val value = when {
|
val value = when {
|
||||||
j >= index -> {
|
j >= index -> {
|
||||||
fromArgs[j--]
|
callArgs[j--]
|
||||||
}
|
}
|
||||||
|
|
||||||
a.defaultValue != null -> a.defaultValue.execute(context)
|
a.defaultValue != null -> a.defaultValue.execute(context)
|
||||||
@@ -74,16 +88,16 @@ data class ArgsDeclaration(val params: List<Item>, val endTokenType: Token.Type)
|
|||||||
fun processEllipsis(index: Int, toFromIndex: Int) {
|
fun processEllipsis(index: Int, toFromIndex: Int) {
|
||||||
val a = params[index]
|
val a = params[index]
|
||||||
val l = if (index > toFromIndex) ObjList()
|
val l = if (index > toFromIndex) ObjList()
|
||||||
else ObjList(fromArgs.values.subList(index, toFromIndex + 1).toMutableList())
|
else ObjList(callArgs.subList(index, toFromIndex + 1).toMutableList())
|
||||||
assign(a, l)
|
assign(a, l)
|
||||||
}
|
}
|
||||||
|
|
||||||
val leftIndex = processHead(0)
|
val leftIndex = processHead(0)
|
||||||
if (leftIndex < params.size) {
|
if (leftIndex < paramsSize) {
|
||||||
val end = processTail(leftIndex)
|
val end = processTail(leftIndex)
|
||||||
processEllipsis(leftIndex, end)
|
processEllipsis(leftIndex, end)
|
||||||
} else {
|
} else {
|
||||||
if (leftIndex < fromArgs.size)
|
if (leftIndex < callArgs.size)
|
||||||
context.raiseArgumentError("too many arguments for the call")
|
context.raiseArgumentError("too many arguments for the call")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,53 +2,40 @@ package net.sergeych.lyng
|
|||||||
|
|
||||||
data class ParsedArgument(val value: Statement, val pos: Pos, val isSplat: Boolean = false)
|
data class ParsedArgument(val value: Statement, val pos: Pos, val isSplat: Boolean = false)
|
||||||
|
|
||||||
suspend fun Collection<ParsedArgument>.toArguments(context: Context): Arguments {
|
suspend fun Collection<ParsedArgument>.toArguments(context: Context,tailBlockMode: Boolean): Arguments {
|
||||||
val list = mutableListOf<Arguments.Info>()
|
val list = mutableListOf<Obj>()
|
||||||
|
|
||||||
for (x in this) {
|
for (x in this) {
|
||||||
val value = x.value.execute(context)
|
val value = x.value.execute(context)
|
||||||
if (x.isSplat) {
|
if (x.isSplat) {
|
||||||
when {
|
when {
|
||||||
value is ObjList -> {
|
value is ObjList -> {
|
||||||
for (subitem in value.list) list.add(Arguments.Info(subitem, x.pos))
|
for (subitem in value.list) list.add(subitem)
|
||||||
}
|
}
|
||||||
|
|
||||||
value.isInstanceOf(ObjIterable) -> {
|
value.isInstanceOf(ObjIterable) -> {
|
||||||
val i = (value.invokeInstanceMethod(context, "toList") as ObjList).list
|
val i = (value.invokeInstanceMethod(context, "toList") as ObjList).list
|
||||||
i.forEach { list.add(Arguments.Info(it, x.pos)) }
|
i.forEach { list.add(it) }
|
||||||
}
|
}
|
||||||
|
|
||||||
else -> context.raiseClassCastError("expected list of objects for splat argument")
|
else -> context.raiseClassCastError("expected list of objects for splat argument")
|
||||||
}
|
}
|
||||||
} else
|
} else
|
||||||
list.add(Arguments.Info(value, x.pos))
|
list.add(value)
|
||||||
}
|
}
|
||||||
return Arguments(list)
|
return Arguments(list,tailBlockMode)
|
||||||
}
|
}
|
||||||
|
|
||||||
data class Arguments(val list: List<Info>) : Iterable<Obj> {
|
data class Arguments(val list: List<Obj>,val tailBlockMode: Boolean = false) : List<Obj> by list {
|
||||||
|
|
||||||
data class Info(val value: Obj, val pos: Pos)
|
fun firstAndOnly(pos: Pos = Pos.UNKNOWN): Obj {
|
||||||
|
if (list.size != 1) throw ScriptError(pos, "expected one argument, got ${list.size}")
|
||||||
val size by list::size
|
return list.first()
|
||||||
|
|
||||||
operator fun get(index: Int): Obj = list[index].value
|
|
||||||
|
|
||||||
val values: List<Obj> by lazy { list.map { it.value } }
|
|
||||||
|
|
||||||
fun firstAndOnly(): Obj {
|
|
||||||
if (list.size != 1) throw IllegalArgumentException("Expected one argument, got ${list.size}")
|
|
||||||
return list.first().value
|
|
||||||
}
|
}
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
val EMPTY = Arguments(emptyList())
|
val EMPTY = Arguments(emptyList())
|
||||||
fun from(values: Collection<Obj>) = Arguments(values.map { Info(it, Pos.UNKNOWN) })
|
fun from(values: Collection<Obj>) = Arguments(values.toList())
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun iterator(): Iterator<Obj> {
|
|
||||||
return list.map { it.value }.iterator()
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -140,7 +140,7 @@ class Compiler(
|
|||||||
Token.Type.LPAREN -> {
|
Token.Type.LPAREN -> {
|
||||||
cc.next()
|
cc.next()
|
||||||
// instance method call
|
// instance method call
|
||||||
val args = parseArgs(cc)
|
val args = parseArgs(cc).first
|
||||||
isCall = true
|
isCall = true
|
||||||
operand = Accessor { context ->
|
operand = Accessor { context ->
|
||||||
context.pos = next.pos
|
context.pos = next.pos
|
||||||
@@ -149,7 +149,7 @@ class Compiler(
|
|||||||
v.invokeInstanceMethod(
|
v.invokeInstanceMethod(
|
||||||
context,
|
context,
|
||||||
next.value,
|
next.value,
|
||||||
args.toArguments(context)
|
args.toArguments(context,false)
|
||||||
), isMutable = false
|
), isMutable = false
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -170,7 +170,7 @@ class Compiler(
|
|||||||
v.invokeInstanceMethod(
|
v.invokeInstanceMethod(
|
||||||
context,
|
context,
|
||||||
next.value,
|
next.value,
|
||||||
Arguments(listOf(Arguments.Info(lambda, t.pos)))
|
Arguments(listOf(lambda),true)
|
||||||
), isMutable = false
|
), isMutable = false
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -379,7 +379,7 @@ class Compiler(
|
|||||||
val context = closure!!.copy(pos, args)
|
val context = closure!!.copy(pos, args)
|
||||||
if (argsDeclaration == null) {
|
if (argsDeclaration == null) {
|
||||||
// no args: automatic var 'it'
|
// no args: automatic var 'it'
|
||||||
val l = args.values
|
val l = args.list
|
||||||
val itValue: Obj = when (l.size) {
|
val itValue: Obj = when (l.size) {
|
||||||
// no args: it == void
|
// no args: it == void
|
||||||
0 -> ObjVoid
|
0 -> ObjVoid
|
||||||
@@ -552,7 +552,11 @@ class Compiler(
|
|||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun parseArgs(cc: CompilerContext): List<ParsedArgument> {
|
/**
|
||||||
|
* Parse arguments list during the call and detect last block argument
|
||||||
|
* _following the parenthesis_ call: `(1,2) { ... }`
|
||||||
|
*/
|
||||||
|
private fun parseArgs(cc: CompilerContext): Pair<List<ParsedArgument>, Boolean> {
|
||||||
|
|
||||||
val args = mutableListOf<ParsedArgument>()
|
val args = mutableListOf<ParsedArgument>()
|
||||||
do {
|
do {
|
||||||
@@ -578,6 +582,7 @@ class Compiler(
|
|||||||
// block after?
|
// block after?
|
||||||
val pos = cc.savePos()
|
val pos = cc.savePos()
|
||||||
val end = cc.next()
|
val end = cc.next()
|
||||||
|
var lastBlockArgument = false
|
||||||
if (end.type == Token.Type.LBRACE) {
|
if (end.type == Token.Type.LBRACE) {
|
||||||
// last argument - callable
|
// last argument - callable
|
||||||
val callableAccessor = parseLambdaExpression(cc)
|
val callableAccessor = parseLambdaExpression(cc)
|
||||||
@@ -588,14 +593,16 @@ class Compiler(
|
|||||||
},
|
},
|
||||||
end.pos
|
end.pos
|
||||||
)
|
)
|
||||||
|
lastBlockArgument = true
|
||||||
} else
|
} else
|
||||||
cc.restorePos(pos)
|
cc.restorePos(pos)
|
||||||
return args
|
return args to lastBlockArgument
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
private fun parseFunctionCall(cc: CompilerContext, left: Accessor, blockArgument: Boolean): Accessor {
|
private fun parseFunctionCall(cc: CompilerContext, left: Accessor, blockArgument: Boolean): Accessor {
|
||||||
// insofar, functions always return lvalue
|
// insofar, functions always return lvalue
|
||||||
|
var detectedBlockArgument = blockArgument
|
||||||
val args = if (blockArgument) {
|
val args = if (blockArgument) {
|
||||||
val blockArg = ParsedArgument(
|
val blockArg = ParsedArgument(
|
||||||
parseExpression(cc)
|
parseExpression(cc)
|
||||||
@@ -603,7 +610,9 @@ class Compiler(
|
|||||||
)
|
)
|
||||||
listOf(blockArg)
|
listOf(blockArg)
|
||||||
} else {
|
} else {
|
||||||
parseArgs(cc)
|
val r = parseArgs(cc)
|
||||||
|
detectedBlockArgument = r.second
|
||||||
|
r.first
|
||||||
}
|
}
|
||||||
|
|
||||||
return Accessor { context ->
|
return Accessor { context ->
|
||||||
@@ -611,7 +620,7 @@ class Compiler(
|
|||||||
v.value.callOn(
|
v.value.callOn(
|
||||||
context.copy(
|
context.copy(
|
||||||
context.pos,
|
context.pos,
|
||||||
args.toArguments(context)
|
args.toArguments(context, detectedBlockArgument)
|
||||||
// Arguments(
|
// Arguments(
|
||||||
// args.map { Arguments.Info((it.value as Statement).execute(context), it.pos) }
|
// args.map { Arguments.Info((it.value as Statement).execute(context), it.pos) }
|
||||||
// ),
|
// ),
|
||||||
@@ -701,6 +710,7 @@ class Compiler(
|
|||||||
"val" -> parseVarDeclaration(id.value, false, cc)
|
"val" -> parseVarDeclaration(id.value, false, cc)
|
||||||
"var" -> parseVarDeclaration(id.value, true, cc)
|
"var" -> parseVarDeclaration(id.value, true, cc)
|
||||||
"while" -> parseWhileStatement(cc)
|
"while" -> parseWhileStatement(cc)
|
||||||
|
"do" -> parseDoWhileStatement(cc)
|
||||||
"for" -> parseForStatement(cc)
|
"for" -> parseForStatement(cc)
|
||||||
"break" -> parseBreakStatement(id.pos, cc)
|
"break" -> parseBreakStatement(id.pos, cc)
|
||||||
"continue" -> parseContinueStatement(id.pos, cc)
|
"continue" -> parseContinueStatement(id.pos, cc)
|
||||||
@@ -935,6 +945,59 @@ class Compiler(
|
|||||||
return elseStatement?.execute(forContext) ?: result
|
return elseStatement?.execute(forContext) ?: result
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Suppress("UNUSED_VARIABLE")
|
||||||
|
private fun parseDoWhileStatement(cc: CompilerContext): Statement {
|
||||||
|
val label = getLabel(cc)?.also { cc.labels += it }
|
||||||
|
val (breakFound, body) = cc.parseLoop {
|
||||||
|
parseStatement(cc) ?: throw ScriptError(cc.currentPos(), "Bad while statement: expected statement")
|
||||||
|
}
|
||||||
|
label?.also { cc.labels -= it }
|
||||||
|
|
||||||
|
cc.skipTokens(Token.Type.NEWLINE)
|
||||||
|
|
||||||
|
val t = cc.next()
|
||||||
|
if( t.type != Token.Type.ID && t.value != "while" )
|
||||||
|
cc.skipTokenOfType(Token.Type.LPAREN, "expected '(' here")
|
||||||
|
|
||||||
|
val conditionStart = ensureLparen(cc)
|
||||||
|
val condition =
|
||||||
|
parseExpression(cc) ?: throw ScriptError(conditionStart, "Bad while statement: expected expression")
|
||||||
|
ensureRparen(cc)
|
||||||
|
|
||||||
|
cc.skipTokenOfType(Token.Type.NEWLINE, isOptional = true)
|
||||||
|
val elseStatement = if (cc.next().let { it.type == Token.Type.ID && it.value == "else" }) {
|
||||||
|
parseStatement(cc)
|
||||||
|
} else {
|
||||||
|
cc.previous()
|
||||||
|
null
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
return statement(body.pos) {
|
||||||
|
var wasBroken = false
|
||||||
|
var result: Obj = ObjVoid
|
||||||
|
lateinit var doContext: Context
|
||||||
|
do {
|
||||||
|
doContext = it.copy().apply { skipContextCreation = true }
|
||||||
|
try {
|
||||||
|
result = body.execute(doContext)
|
||||||
|
}
|
||||||
|
catch( e: LoopBreakContinueException) {
|
||||||
|
if( e.label == label || e.label == null ) {
|
||||||
|
if( e.doContinue ) continue
|
||||||
|
else {
|
||||||
|
result = e.result
|
||||||
|
wasBroken = true
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} while( condition.execute(doContext).toBool() )
|
||||||
|
if( !wasBroken ) elseStatement?.let { s -> result = s.execute(it) }
|
||||||
|
result
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private fun parseWhileStatement(cc: CompilerContext): Statement {
|
private fun parseWhileStatement(cc: CompilerContext): Statement {
|
||||||
val label = getLabel(cc)?.also { cc.labels += it }
|
val label = getLabel(cc)?.also { cc.labels += it }
|
||||||
val start = ensureLparen(cc)
|
val start = ensureLparen(cc)
|
||||||
@@ -1140,7 +1203,7 @@ class Compiler(
|
|||||||
val block = parseScript(startPos, cc)
|
val block = parseScript(startPos, cc)
|
||||||
return statement(startPos) {
|
return statement(startPos) {
|
||||||
// block run on inner context:
|
// block run on inner context:
|
||||||
block.execute(it.copy(startPos))
|
block.execute(if( it.skipContextCreation ) it else it.copy(startPos))
|
||||||
}.also {
|
}.also {
|
||||||
val t1 = cc.next()
|
val t1 = cc.next()
|
||||||
if (t1.type != Token.Type.RBRACE)
|
if (t1.type != Token.Type.RBRACE)
|
||||||
@@ -1175,7 +1238,7 @@ class Compiler(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
val initialExpression = if (setNull) null else parseExpression(tokens)
|
val initialExpression = if (setNull) null else parseStatement(tokens, true)
|
||||||
?: throw ScriptError(eqToken.pos, "Expected initializer expression")
|
?: throw ScriptError(eqToken.pos, "Expected initializer expression")
|
||||||
|
|
||||||
return statement(nameToken.pos) { context ->
|
return statement(nameToken.pos) { context ->
|
||||||
@@ -1187,7 +1250,7 @@ class Compiler(
|
|||||||
val initValue = initialExpression?.execute(context)?.byValueCopy() ?: ObjNull
|
val initValue = initialExpression?.execute(context)?.byValueCopy() ?: ObjNull
|
||||||
|
|
||||||
context.addItem(name, mutable, initValue, visibility)
|
context.addItem(name, mutable, initValue, visibility)
|
||||||
ObjVoid
|
initValue
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -134,6 +134,13 @@ internal class CompilerContext(val tokens: List<Token>) {
|
|||||||
return default
|
return default
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// fun expectKeyword(vararg keyword: String): String {
|
||||||
|
// val t = next()
|
||||||
|
// if (t.type != Token.Type.ID && t.value !in keyword) {
|
||||||
|
// throw ScriptError(t.pos, "expected one of ${keyword.joinToString()}")
|
||||||
|
//
|
||||||
|
// }
|
||||||
|
|
||||||
// data class ReturnScope(val needCatch: Boolean = false)
|
// data class ReturnScope(val needCatch: Boolean = false)
|
||||||
|
|
||||||
// private val
|
// private val
|
||||||
|
|||||||
@@ -4,7 +4,8 @@ class Context(
|
|||||||
val parent: Context?,
|
val parent: Context?,
|
||||||
val args: Arguments = Arguments.EMPTY,
|
val args: Arguments = Arguments.EMPTY,
|
||||||
var pos: Pos = Pos.builtIn,
|
var pos: Pos = Pos.builtIn,
|
||||||
val thisObj: Obj = ObjVoid
|
val thisObj: Obj = ObjVoid,
|
||||||
|
var skipContextCreation: Boolean = false,
|
||||||
) {
|
) {
|
||||||
constructor(
|
constructor(
|
||||||
args: Arguments = Arguments.EMPTY,
|
args: Arguments = Arguments.EMPTY,
|
||||||
@@ -41,8 +42,8 @@ class Context(
|
|||||||
|
|
||||||
inline fun <reified T : Obj> requiredArg(index: Int): T {
|
inline fun <reified T : Obj> requiredArg(index: Int): T {
|
||||||
if (args.list.size <= index) raiseError("Expected at least ${index + 1} argument, got ${args.list.size}")
|
if (args.list.size <= index) raiseError("Expected at least ${index + 1} argument, got ${args.list.size}")
|
||||||
return (args.list[index].value as? T)
|
return (args.list[index] as? T)
|
||||||
?: raiseClassCastError("Expected type ${T::class.simpleName}, got ${args.list[index].value::class.simpleName}")
|
?: raiseClassCastError("Expected type ${T::class.simpleName}, got ${args.list[index]::class.simpleName}")
|
||||||
}
|
}
|
||||||
|
|
||||||
inline fun <reified T : Obj> requireOnlyArg(): T {
|
inline fun <reified T : Obj> requireOnlyArg(): T {
|
||||||
@@ -80,7 +81,7 @@ class Context(
|
|||||||
value: Obj,
|
value: Obj,
|
||||||
visibility: Visibility = Visibility.Public
|
visibility: Visibility = Visibility.Public
|
||||||
): ObjRecord {
|
): ObjRecord {
|
||||||
return ObjRecord(value, isMutable, visibility).also { objects.put(name, it) }
|
return ObjRecord(value, isMutable, visibility).also { objects[name] = it }
|
||||||
}
|
}
|
||||||
|
|
||||||
fun getOrCreateNamespace(name: String): ObjClass {
|
fun getOrCreateNamespace(name: String): ObjClass {
|
||||||
|
|||||||
@@ -61,7 +61,7 @@ open class Obj {
|
|||||||
fun isInstanceOf(someClass: Obj) = someClass === objClass || objClass.allParentsSet.contains(someClass)
|
fun isInstanceOf(someClass: Obj) = someClass === objClass || objClass.allParentsSet.contains(someClass)
|
||||||
|
|
||||||
suspend fun invokeInstanceMethod(context: Context, name: String, vararg args: Obj): Obj =
|
suspend fun invokeInstanceMethod(context: Context, name: String, vararg args: Obj): Obj =
|
||||||
invokeInstanceMethod(context, name, Arguments(args.map { Arguments.Info(it, context.pos) }))
|
invokeInstanceMethod(context, name, Arguments(args.toList()))
|
||||||
|
|
||||||
inline suspend fun <reified T : Obj> callMethod(
|
inline suspend fun <reified T : Obj> callMethod(
|
||||||
context: Context,
|
context: Context,
|
||||||
@@ -218,7 +218,7 @@ open class Obj {
|
|||||||
callOn(
|
callOn(
|
||||||
context.copy(
|
context.copy(
|
||||||
context.pos,
|
context.pos,
|
||||||
args = Arguments(args.map { Arguments.Info(it, context.pos) }),
|
args = Arguments(args.toList()),
|
||||||
newThisObj = thisObj
|
newThisObj = thisObj
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
@@ -286,6 +286,8 @@ object ObjNull : Obj() {
|
|||||||
override fun equals(other: Any?): Boolean {
|
override fun equals(other: Any?): Boolean {
|
||||||
return other is ObjNull || other == null
|
return other is ObjNull || other == null
|
||||||
}
|
}
|
||||||
|
|
||||||
|
override fun toString(): String = "null"
|
||||||
}
|
}
|
||||||
|
|
||||||
interface Numeric {
|
interface Numeric {
|
||||||
|
|||||||
@@ -40,6 +40,32 @@ data class ObjString(val value: String) : Obj() {
|
|||||||
addConst("length",
|
addConst("length",
|
||||||
statement { ObjInt(thisAs<ObjString>().value.length.toLong()) }
|
statement { ObjInt(thisAs<ObjString>().value.length.toLong()) }
|
||||||
)
|
)
|
||||||
|
addFn("takeLast") {
|
||||||
|
thisAs<ObjString>().value.takeLast(
|
||||||
|
requiredArg<ObjInt>(0).toInt()
|
||||||
|
).let(::ObjString)
|
||||||
|
}
|
||||||
|
addFn("take") {
|
||||||
|
thisAs<ObjString>().value.take(
|
||||||
|
requiredArg<ObjInt>(0).toInt()
|
||||||
|
).let(::ObjString)
|
||||||
|
}
|
||||||
|
addFn("drop") {
|
||||||
|
thisAs<ObjString>().value.drop(
|
||||||
|
requiredArg<ObjInt>(0).toInt()
|
||||||
|
).let(::ObjString)
|
||||||
|
}
|
||||||
|
addFn("dropLast") {
|
||||||
|
thisAs<ObjString>().value.dropLast(
|
||||||
|
requiredArg<ObjInt>(0).toInt()
|
||||||
|
).let(::ObjString)
|
||||||
|
}
|
||||||
|
addFn("lower") {
|
||||||
|
thisAs<ObjString>().value.lowercase().let(::ObjString)
|
||||||
|
}
|
||||||
|
addFn("upper") {
|
||||||
|
thisAs<ObjString>().value.uppercase().let(::ObjString)
|
||||||
|
}
|
||||||
addFn("size") { ObjInt(thisAs<ObjString>().value.length.toLong()) }
|
addFn("size") { ObjInt(thisAs<ObjString>().value.length.toLong()) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ class Script(
|
|||||||
return lastResult
|
return lastResult
|
||||||
}
|
}
|
||||||
|
|
||||||
suspend fun execute() = execute(defaultContext.copy(pos))
|
suspend fun execute() = execute(defaultContext.copy(pos = pos))
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
val defaultContext: Context = Context().apply {
|
val defaultContext: Context = Context().apply {
|
||||||
|
|||||||
@@ -174,7 +174,7 @@ class ScriptTest {
|
|||||||
fun varsAndConstsTest() = runTest {
|
fun varsAndConstsTest() = runTest {
|
||||||
val context = Context(pos = Pos.builtIn)
|
val context = Context(pos = Pos.builtIn)
|
||||||
assertEquals(
|
assertEquals(
|
||||||
ObjVoid, context.eval(
|
ObjInt(3L), context.eval(
|
||||||
"""
|
"""
|
||||||
val a = 17
|
val a = 17
|
||||||
var b = 3
|
var b = 3
|
||||||
@@ -434,6 +434,16 @@ class ScriptTest {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun whileAssignTest() = runTest {
|
||||||
|
eval("""
|
||||||
|
var t = 0
|
||||||
|
val x = while( t < 5 ) { t++ }
|
||||||
|
// last returned value is 4 - when t was 5 body was not executed
|
||||||
|
assertEquals( 4, x )
|
||||||
|
""".trimIndent())
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun whileTest() = runTest {
|
fun whileTest() = runTest {
|
||||||
assertEquals(
|
assertEquals(
|
||||||
@@ -1585,16 +1595,105 @@ class ScriptTest {
|
|||||||
assertEquals("1.0E-6", eval("1e-6").toString())
|
assertEquals("1.0E-6", eval("1e-6").toString())
|
||||||
}
|
}
|
||||||
|
|
||||||
// @Test
|
@Test
|
||||||
// fun testLambdaLastArgAfterDetault() = runTest {
|
fun testCallLastBlockAfterDetault() = runTest {
|
||||||
// val c = Context()
|
eval("""
|
||||||
// eval("""
|
// this means last is lambda:
|
||||||
// // this means last is lambda:
|
fun f(e=1, f) {
|
||||||
// fun f(e=1, f) {
|
"e="+e+"f="+f()
|
||||||
// "e="+e+"f="+f()
|
}
|
||||||
// }
|
assertEquals("e=1f=xx", f { "xx" })
|
||||||
// assertEquals("e=1f=xx", f { "xx" })
|
""".trimIndent())
|
||||||
// """.trimIndent())
|
|
||||||
//
|
}
|
||||||
// }
|
|
||||||
|
@Test
|
||||||
|
fun testCallLastBlockWithEllipsis() = runTest {
|
||||||
|
eval("""
|
||||||
|
// this means last is lambda:
|
||||||
|
fun f(e..., f) {
|
||||||
|
"e="+e+"f="+f()
|
||||||
|
}
|
||||||
|
assertEquals("e=[]f=xx", f { "xx" })
|
||||||
|
assertEquals("e=[1, 2]f=xx", f(1,2) { "xx" })
|
||||||
|
""".trimIndent())
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testMethodCallLastBlockAfterDefault() = runTest {
|
||||||
|
eval("""
|
||||||
|
class Foo {
|
||||||
|
// this means last is lambda:
|
||||||
|
fun f(e=1, f) {
|
||||||
|
"e="+e+"f="+f()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val f = Foo()
|
||||||
|
assertEquals("e=1f=xx", f.f { "xx" })
|
||||||
|
""".trimIndent())
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testMethodCallLastBlockWithEllipsis() = runTest {
|
||||||
|
eval("""
|
||||||
|
class Foo {
|
||||||
|
// this means last is lambda:
|
||||||
|
fun f(e..., f) {
|
||||||
|
"e="+e+"f="+f()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val f = Foo()
|
||||||
|
assertEquals("e=[]f=xx", f.f { "xx" })
|
||||||
|
assertEquals("e=[1, 2]f=xx", f.f(1,2) { "xx" })
|
||||||
|
""".trimIndent())
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun nationalCharsTest() = runTest {
|
||||||
|
eval("""
|
||||||
|
fun сумма_ряда(x, погрешность=0.0001, f) {
|
||||||
|
var сумма = 0
|
||||||
|
for( n in 1..100000) {
|
||||||
|
val следующая_сумма = сумма + f(x, n)
|
||||||
|
if( n > 1 && abs(следующая_сумма - сумма) < погрешность )
|
||||||
|
break следующая_сумма
|
||||||
|
сумма = следующая_сумма
|
||||||
|
}
|
||||||
|
else null
|
||||||
|
}
|
||||||
|
val x = сумма_ряда(1) { x, n ->
|
||||||
|
val sign = if( n % 2 == 1 ) 1 else -1
|
||||||
|
sign * pow(x, n) / n
|
||||||
|
}
|
||||||
|
assert( x - ln(2) < 0.001 )
|
||||||
|
""".trimIndent())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun doWhileSimpleTest() = runTest {
|
||||||
|
eval("""
|
||||||
|
var sum = 0
|
||||||
|
var x = do {
|
||||||
|
val s = sum
|
||||||
|
sum += 1
|
||||||
|
} while( s < 10 )
|
||||||
|
assertEquals(11, x)
|
||||||
|
""".trimIndent())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun testFailDoWhileSample1() = runTest {
|
||||||
|
eval("""
|
||||||
|
fun readLine() { "done: result" }
|
||||||
|
val result = do {
|
||||||
|
val line = readLine()
|
||||||
|
} while( !line.startsWith("done:") )
|
||||||
|
assertEquals("result", result.drop(6))
|
||||||
|
result
|
||||||
|
""".trimIndent())
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user