commit 6b42229dc4866f0cb477d7b56c2e706267479d5a
parent 1b73c202256637c6303cd254a3d69084a7a16572
Author: Jan Dankert <develop@jandankert.de>
Date: Sun, 26 Jun 2022 16:04:19 +0200
Fetched from upstream; More examples.
Diffstat:
3 files changed, 94 insertions(+), 5 deletions(-)
diff --git a/dsl/DslLexer.class.php b/dsl/DslLexer.class.php
@@ -95,7 +95,12 @@ class DslLexer
throw new DslParserException("Unclosed string",$line);
if ( $char == '\\') {
$char = array_shift($chars);
- $value .= $char;
+ if ( $char == 'n' )
+ $value = "\n";
+ elseif ( $char == 't' )
+ $value = "\t";
+ else
+ $value .= $char;
}
elseif ($char != $textEncloser) {
$value .= $char;
diff --git a/dsl/standard/Script.class.php b/dsl/standard/Script.class.php
@@ -0,0 +1,56 @@
+<?php
+
+namespace dsl\standard;
+
+use dsl\ast\DslStatement;
+use dsl\context\DslObject;
+use dsl\DslToken;
+
+class Script implements DslObject
+{
+ /**
+ * @var DslToken[]
+ */
+ private $tokens;
+
+ /**
+ * @var DslStatement
+ */
+ private $ast;
+
+ /**
+ * @param $tokens DslToken[]
+ * @param $ast DslStatement
+ */
+ public function __construct($tokens, $ast )
+ {
+ $this->tokens = $tokens;
+ $this->ast = $ast;
+ }
+
+ public function getToken()
+ {
+ return implode("\n",$this->tokens);
+ }
+
+
+ public function getSource()
+ {
+ $line = 0;
+ $source = '';
+
+ foreach( $this->tokens as $token ) {
+
+ $source .= ($line != $token->lineNumber ? "\n" . str_pad($token->lineNumber, 4, '0', STR_PAD_LEFT).': ' : '') . $token->value;
+ $line = $token->lineNumber;
+ }
+
+ return $source."\n";
+ }
+
+
+ public function getSyntaxTree()
+ {
+ return print_r($this->ast,true);
+ }
+}
+\ No newline at end of file
diff --git a/index.php b/index.php
@@ -20,16 +20,43 @@ require('./autoload.php');
<h1>Script Sandbox</h1>
<p>Script sandbox for PHP. The syntax is a subset of Javascript. The interpreter is supporting functions, full arithmetic calculations, for-loops, if-else statements.
</p>
- <?php $code = $_POST['code'] ?: <<<DEF
+ <?php $code = @$_POST['code'] ?: <<<DEF
// Script sandbox
// Feel free to write some code here....
-write( "test" );
+//write( "test" );
/**
-*/
-function name() {
+ * functions without parameters
+ */
+function something() {
return "something";
}
+
+write( "I wrote " + something() + "\\n" );
+
+/**
+ * functions with parameters
+ */
+function sayName( name ) {
+ write( "your name is " + name + "\\n" );
+}
+
+sayName("Alice");
+
+// Arithmetic magic
+write( "Arithmetic magic: 1 + 2 * (3 + 2) = " );
+write( 1 + 2 * (3 + 2) );
+write( "\\n" );
+
+
+
+// lists...
+names = Array.of("Alice","Bob",something() );
+
+for( name of names ) {
+ write( "A name: " + name + "\\n");
+}
+
DEF
; ?>