├── .github └── workflows │ └── build-and-test.yaml ├── .gitignore ├── .gitmodules ├── .vscode ├── launch.json └── tasks.json ├── LICENSE ├── README.md ├── build ├── bundle-packages.ts ├── generate-ast-helper-code.ts └── tsconfig.json ├── docs ├── expression-language.md ├── exprlang-ast.md ├── exprlang-lexer.md ├── exprlang-parser.md ├── exprlang-vm.md ├── import.md ├── onelang-ast.md ├── onelang-project-structure.md ├── planning │ └── language-support.md ├── project-structure.md └── transformations.md ├── langs ├── NativeResolvers │ ├── GenericTransforms.yaml │ ├── csharp.ts │ ├── php.ts │ ├── ruby.ts │ └── typescript.ts ├── cpp.yaml ├── csharp.yaml ├── go.yaml ├── java.yaml ├── javascript.yaml ├── perl.yaml ├── php.yaml ├── python.yaml ├── ruby.yaml ├── swift.yaml └── typescript.yaml ├── lib └── .npmignore ├── onepkg ├── One.Ast-v0.1 │ └── index.d.ts ├── One.Core-v0.1 │ ├── index.d.ts │ └── index.js ├── One.File-v0.1 │ ├── index.d.ts │ └── index.js ├── One.Json-v0.1 │ ├── index.d.ts │ └── index.js ├── One.Reflect-v0.1 │ ├── index.d.ts │ └── index.js └── One.Yaml-v0.1 │ ├── index.d.ts │ └── index.js ├── package-lock.json ├── package.json ├── packages ├── implementations │ ├── OneLang-BigInteger-Native-v0.1 │ │ └── package.yaml │ ├── OneLang-BigIntegerJS-v0.1 │ │ └── package.yaml │ ├── OneLang-Console-v0.1 │ │ ├── Java │ │ │ └── JsToJava.yaml │ │ └── package.yaml │ ├── OneLang-Core-v0.1 │ │ ├── CSharp │ │ │ ├── JsToCSharp.yaml │ │ │ └── src │ │ │ │ ├── Array.cs │ │ │ │ ├── Error.cs │ │ │ │ ├── ExtensionMethods.cs │ │ │ │ ├── Global.cs │ │ │ │ ├── Map.cs │ │ │ │ ├── Math.cs │ │ │ │ ├── Object.cs │ │ │ │ ├── Promise.cs │ │ │ │ ├── RegExp.cs │ │ │ │ ├── Set.cs │ │ │ │ └── console.cs │ │ ├── Java │ │ │ ├── JsToJava.yaml │ │ │ └── src │ │ │ │ ├── ExceptionHelper.java │ │ │ │ ├── Objects.java │ │ │ │ ├── One.java │ │ │ │ ├── RegExp.java │ │ │ │ ├── StdArrayHelper.java │ │ │ │ └── console.java │ │ ├── PHP │ │ │ ├── JsToPhp.yaml │ │ │ └── src │ │ │ │ ├── ArrayHelper.php │ │ │ │ ├── Array_.php │ │ │ │ ├── Error.php │ │ │ │ ├── Map.php │ │ │ │ ├── RegExp.php │ │ │ │ ├── Set.php │ │ │ │ └── console.php │ │ ├── Python │ │ │ ├── JsToPython.yaml │ │ │ └── src │ │ │ │ ├── OneCore.py │ │ │ │ └── __init__.py │ │ ├── langs │ │ │ ├── cpp.yaml │ │ │ ├── csharp.yaml │ │ │ ├── go.yaml │ │ │ ├── java.yaml │ │ │ ├── javascript.yaml │ │ │ ├── perl.yaml │ │ │ ├── php.yaml │ │ │ ├── python.yaml │ │ │ ├── ruby.yaml │ │ │ ├── swift.yaml │ │ │ └── typescript.yaml │ │ ├── native │ │ │ ├── one.go │ │ │ ├── one.hpp │ │ │ ├── one.pl │ │ │ └── one.swift │ │ └── package.yaml │ ├── OneLang-File-v0.1 │ │ ├── CPP │ │ │ └── src │ │ │ │ ├── OneFile.cpp │ │ │ │ └── OneFile.hpp │ │ ├── CSharp │ │ │ └── src │ │ │ │ └── OneFile.cs │ │ ├── Java │ │ │ └── src │ │ │ │ └── OneFile.java │ │ ├── PHP │ │ │ ├── OneFile.yaml │ │ │ └── src │ │ │ │ └── OneFile.php │ │ ├── Python │ │ │ └── src │ │ │ │ ├── OneFile.py │ │ │ │ └── __init__.py │ │ ├── langs │ │ │ ├── cpp.yaml │ │ │ ├── csharp.yaml │ │ │ ├── go.yaml │ │ │ ├── java.yaml │ │ │ ├── javascript.yaml │ │ │ ├── perl.yaml │ │ │ ├── php.yaml │ │ │ ├── python.yaml │ │ │ ├── ruby.yaml │ │ │ ├── swift.yaml │ │ │ └── typescript.yaml │ │ └── package.yaml │ ├── OneLang-Json-v0.1 │ │ ├── CSharp │ │ │ └── src │ │ │ │ ├── JSON.cs │ │ │ │ └── OneJson.cs │ │ ├── Java │ │ │ ├── JsToJava.yaml │ │ │ └── src │ │ │ │ ├── JSON.java │ │ │ │ ├── OneJObject.java │ │ │ │ ├── OneJValue.java │ │ │ │ └── OneJson.java │ │ ├── PHP │ │ │ ├── JsToPhp.yaml │ │ │ └── src │ │ │ │ └── OneJson.php │ │ ├── Python │ │ │ ├── JsToPython.yaml │ │ │ └── src │ │ │ │ ├── OneJson.py │ │ │ │ └── __init__.py │ │ ├── langs │ │ │ ├── csharp.yaml │ │ │ ├── go.yaml │ │ │ ├── java.yaml │ │ │ ├── javascript.yaml │ │ │ ├── php.yaml │ │ │ ├── python.yaml │ │ │ ├── ruby.yaml │ │ │ ├── swift.yaml │ │ │ └── typescript.yaml │ │ └── package.yaml │ ├── OneLang-Reflect-v0.1 │ │ ├── CSharp │ │ │ └── src │ │ │ │ └── ReflectedValue.cs │ │ ├── Java │ │ │ └── src │ │ │ │ └── ReflectedValue.java │ │ ├── langs │ │ │ ├── cpp.yaml │ │ │ ├── csharp.yaml │ │ │ ├── go.yaml │ │ │ ├── java.yaml │ │ │ ├── javascript.yaml │ │ │ ├── perl.yaml │ │ │ ├── php.yaml │ │ │ ├── python.yaml │ │ │ ├── ruby.yaml │ │ │ ├── swift.yaml │ │ │ └── typescript.yaml │ │ ├── native │ │ │ ├── OneReflect.js │ │ │ ├── OneReflect.py │ │ │ ├── OneReflect.rb │ │ │ ├── java │ │ │ │ ├── OneClass.java │ │ │ │ ├── OneField.java │ │ │ │ ├── OneMethod.java │ │ │ │ └── OneReflect.java │ │ │ ├── one.cs │ │ │ ├── one.go │ │ │ ├── one.hpp │ │ │ ├── one.php │ │ │ ├── one.pl │ │ │ ├── one.swift │ │ │ └── one.ts │ │ └── package.yaml │ ├── OneLang-Regex-v0.1 │ │ ├── langs │ │ │ ├── cpp.yaml │ │ │ ├── csharp.yaml │ │ │ ├── go.yaml │ │ │ ├── java.yaml │ │ │ ├── javascript.yaml │ │ │ ├── perl.yaml │ │ │ ├── php.yaml │ │ │ ├── python.yaml │ │ │ ├── ruby.yaml │ │ │ ├── swift.yaml │ │ │ └── typescript.yaml │ │ ├── native │ │ │ ├── OneRegex.js │ │ │ ├── OneRegex.py │ │ │ ├── OneRegex.rb │ │ │ ├── cpp │ │ │ │ ├── OneRegex.cpp │ │ │ │ └── OneRegex.hpp │ │ │ ├── java │ │ │ │ └── io │ │ │ │ │ └── onelang │ │ │ │ │ └── OneRegex.java │ │ │ ├── one.cs │ │ │ ├── one.go │ │ │ ├── one.php │ │ │ ├── one.pl │ │ │ ├── one.swift │ │ │ └── one.ts │ │ └── package.yaml │ └── OneLang-Yaml-v0.1 │ │ ├── CSharp │ │ └── src │ │ │ ├── OneYaml.cs │ │ │ ├── YAML.cs │ │ │ └── YamlValue.cs │ │ ├── Java │ │ └── src │ │ │ ├── OneYaml.java │ │ │ ├── ValueType.java │ │ │ └── YamlValue.java │ │ ├── PHP │ │ └── src │ │ │ └── OneYaml.php │ │ ├── Python │ │ └── src │ │ │ ├── OneYaml.py │ │ │ ├── YamlValue.py │ │ │ └── __init__.py │ │ └── package.yaml └── interfaces │ ├── One.Ast-v0.1 │ ├── index.d.ts │ └── interface.yaml │ ├── One.BigInteger-v0.1 │ ├── index.d.ts │ └── interface.yaml │ ├── One.Console-v0.1 │ ├── index.d.ts │ └── interface.yaml │ ├── One.Core-v0.1 │ ├── index.d.ts │ └── interface.yaml │ ├── One.File-v0.1 │ ├── index.d.ts │ └── interface.yaml │ ├── One.Json-v0.1 │ ├── index.d.ts │ └── interface.yaml │ ├── One.Reflect-v0.1 │ ├── index.d.ts │ └── interface.yaml │ ├── One.Regex-v0.1 │ ├── index.d.ts │ └── interface.yaml │ └── One.Yaml-v0.1 │ ├── index.d.ts │ └── interface.yaml ├── project-templates ├── One.CSharp-v1 │ ├── index.yaml │ └── src │ │ ├── .gitignore │ │ ├── .vscode │ │ ├── launch.json │ │ └── tasks.json │ │ └── CSharp.csproj ├── One.Java-v1 │ ├── index.yaml │ └── src │ │ ├── .classpath │ │ ├── .gitattributes │ │ ├── .gitignore │ │ ├── .project │ │ ├── .settings │ │ └── org.eclipse.buildship.core.prefs │ │ ├── .vscode │ │ ├── launch.json │ │ ├── settings.json │ │ └── tasks.json │ │ ├── build.gradle │ │ ├── gradle │ │ └── wrapper │ │ │ ├── gradle-wrapper.jar │ │ │ └── gradle-wrapper.properties │ │ ├── gradlew │ │ ├── gradlew.bat │ │ └── settings.gradle ├── One.PHP-v1 │ ├── index.yaml │ └── src │ │ ├── OneLoader.php │ │ └── composer.json └── One.Python-v1 │ ├── index.yaml │ └── src │ ├── .gitignore │ ├── .vscode │ └── launch.json │ ├── __init__.py │ └── requirements.txt ├── src ├── Generator │ ├── CsharpGenerator.ts │ ├── GeneratedFile.ts │ ├── IGenerator.ts │ ├── IGeneratorPlugin.ts │ ├── JavaGenerator.ts │ ├── NameUtils.ts │ ├── PhpGenerator.ts │ ├── ProjectGenerator.ts │ ├── PythonGenerator.ts │ └── TemplateFileGeneratorPlugin.ts ├── One │ ├── Ast │ │ ├── AstHelper.ts │ │ ├── AstTypes.ts │ │ ├── Expressions.ts │ │ ├── Interfaces.ts │ │ ├── References.ts │ │ ├── Statements.ts │ │ └── Types.ts │ ├── AstTransformer.ts │ ├── Compiler.ts │ ├── CompilerHelper.ts │ ├── ErrorManager.ts │ ├── ITransformer.ts │ ├── IssueDetectors │ │ └── CircularDependencyDetector.ts │ ├── Serialization │ │ └── JsonSerializer.ts │ └── Transforms │ │ ├── CollectInheritanceInfo.ts │ │ ├── ConvertNullCoalesce.ts │ │ ├── ConvertToMethodCall.ts │ │ ├── DetectMethodCalls.ts │ │ ├── FillAttributesFromTrivia.ts │ │ ├── FillMutabilityInfo.ts │ │ ├── FillParent.ts │ │ ├── InferTypes.ts │ │ ├── InferTypesPlugins │ │ ├── ArrayAndMapLiteralTypeInfer.ts │ │ ├── BasicTypeInfer.ts │ │ ├── Helpers │ │ │ ├── GenericsResolver.ts │ │ │ └── InferTypesPlugin.ts │ │ ├── InferForeachVarType.ts │ │ ├── InferReturnType.ts │ │ ├── LambdaResolver.ts │ │ ├── NullabilityCheckWithNot.ts │ │ ├── ResolveElementAccess.ts │ │ ├── ResolveEnumMemberAccess.ts │ │ ├── ResolveFieldAndPropertyAccess.ts │ │ ├── ResolveFuncCalls.ts │ │ ├── ResolveMethodCalls.ts │ │ ├── ResolveNewCall.ts │ │ └── TypeScriptNullCoalesce.ts │ │ ├── InstanceOfImplicitCast.ts │ │ ├── LambdaCaptureCollector.ts │ │ ├── ResolveGenericTypeIdentifiers.ts │ │ ├── ResolveIdentifiers.ts │ │ ├── ResolveImports.ts │ │ ├── ResolveUnresolvedTypes.ts │ │ └── UseDefaultCallArgsExplicitly.ts ├── Parsers │ ├── Common │ │ ├── ExpressionParser.ts │ │ ├── IParser.ts │ │ ├── NodeManager.ts │ │ ├── Reader.ts │ │ └── Utils.ts │ └── TypeScriptParser.ts ├── StdLib │ ├── PackageBundleSource.ts │ ├── PackageManager.ts │ └── PackagesFolderSource.ts ├── Template │ ├── Nodes.ts │ └── TemplateParser.ts ├── Test │ ├── PackageStateCapture.ts │ ├── TestCase.ts │ ├── TestCases │ │ ├── BasicTests.ts │ │ ├── OneFileTests.ts │ │ └── ProjectGeneratorTest.ts │ └── TestRunner.ts ├── Utils │ ├── ArrayHelper.ts │ ├── StatementDebugger.ts │ └── TSOverviewGenerator.ts └── VM │ ├── ExprVM.ts │ └── Values.ts ├── test ├── src │ ├── CrossCompiledTestRunner.ts │ ├── ExpressionTest.ts │ ├── ProjectTest.ts │ ├── SelfTest.ts │ ├── UtilityTest.ts │ ├── Utils │ │ ├── ArtifactManager.ts │ │ ├── DiffUtils.ts │ │ ├── FolderCacheBundle.ts │ │ ├── TestUtils.ts │ │ └── Underscore.ts │ └── testSuites │ │ └── ParserTest.ts ├── test.js ├── testSuites │ ├── CompilationTest │ │ ├── ArrayTest.ts │ │ ├── BigInteger.ts │ │ ├── BooleanTest.ts │ │ ├── CharacterTest.ts │ │ ├── ConstrInferBug.ts │ │ ├── ConstructorTest.ts │ │ ├── CustomDecoder.ts │ │ ├── EnumAsFieldTest.ts │ │ ├── EnumTest.ts │ │ ├── ExceptionTest.ts │ │ ├── ExplicitGenericTypeTest.ts │ │ ├── ExplicitTypeTest.ts │ │ ├── FakeEnumTest.ts │ │ ├── FileTest.ts │ │ ├── GenericsTest.ts │ │ ├── HelloWorld.ts │ │ ├── HelloWorldRaw.ts │ │ ├── InheritanceTest.ts │ │ ├── JsonParseTest.ts │ │ ├── MapKeyTest.ts │ │ ├── MapTest.ts │ │ ├── MultiLangTest.ts │ │ ├── NumberUnaryIssue.ts │ │ ├── OneLang.ts │ │ ├── OneLang2.ts │ │ ├── ReflectionTest.ts │ │ ├── StdoutTest.ts │ │ ├── StrLenInferIssue.ts │ │ ├── StrReplaceTest.ts │ │ ├── StringTest.ts │ │ ├── StructureTest1.ts │ │ ├── SubstrMatchTest.ts │ │ ├── TemplateString.ts │ │ ├── TernaryTest.ts │ │ └── Test.ts │ ├── CompiledCodeRunner.yaml │ ├── ExprLang-Lexer.yaml │ ├── ExprLang-Parser.yaml │ ├── ExprLang-ParserAst.yaml │ ├── ExprLang-VM.yaml │ ├── OneTemplate.yaml │ └── ProjectTest │ │ ├── ComplexTest01 │ │ ├── src │ │ │ ├── ComplexTest01.ts │ │ │ ├── Model │ │ │ │ ├── Db │ │ │ │ │ ├── Group.ts │ │ │ │ │ └── User.ts │ │ │ │ └── GroupManager.ts │ │ │ └── Utils │ │ │ │ ├── ArrayUtil.ts │ │ │ │ ├── List.ts │ │ │ │ └── StringUtil.ts │ │ └── tsconfig.json │ │ └── ImportTest │ │ ├── src │ │ └── ImportTest.ts │ │ └── tsconfig.json └── tsconfig.json ├── tsconfig.json ├── typings.json ├── watch.sh └── xcompiled-src ├── native ├── CSharp │ ├── .gitignore │ ├── .vscode │ │ ├── launch.json │ │ └── tasks.json │ └── Program.cs ├── Java │ └── src │ │ └── main │ │ └── java │ │ └── Main.java ├── LICENSE ├── PHP │ └── main.php └── Python │ └── main.py ├── one.json └── scripts ├── cleanup_generated_code.sh └── test_all.sh /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | \.DS_Store 3 | node_modules/ 4 | test/lib/ 5 | lib/**/*.d.ts 6 | lib/**/*.js 7 | **/*.js.map 8 | ast\.json 9 | schema\.json 10 | tmp/ 11 | .secret_token 12 | *.tsbuildinfo 13 | build/*.js 14 | packages/bundle.json 15 | dist/ -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "test/artifacts"] 2 | path = test/artifacts 3 | url = https://github.com/onelang/TestArtifacts 4 | [submodule "xcompiled"] 5 | path = xcompiled 6 | url = git@github.com:onelang/OneLang-CrossCompiled.git 7 | -------------------------------------------------------------------------------- /.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | // See https://go.microsoft.com/fwlink/?LinkId=733558 3 | // for the documentation about the tasks.json format 4 | "version": "2.0.0", 5 | "tasks": [ 6 | { 7 | "taskName": "compile", 8 | "command": "node_modules/.bin/tsc", 9 | "isShellCommand": true, 10 | "args": [ 11 | "-w", 12 | "-p", 13 | "." 14 | ], 15 | "showOutput": "silent", 16 | "isBackground": true, 17 | "problemMatcher": "$tsc-watch", 18 | "group": { 19 | "kind": "build", 20 | "isDefault": true 21 | } 22 | }, 23 | { 24 | "label": "Compile Swift", 25 | "type": "shell", 26 | "command": "bash -i tmp_build.sh", 27 | "group": { 28 | "kind": "build", 29 | "isDefault": false 30 | }, 31 | "presentation": { 32 | "reveal": "always", 33 | "panel": "dedicated" 34 | } 35 | } 36 | ] 37 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Tamás Koczka 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /build/bundle-packages.ts: -------------------------------------------------------------------------------- 1 | import 'module-alias/register'; 2 | import { PackagesFolderSource } from "@one/StdLib/PackagesFolderSource"; 3 | import { writeFileSync } from "fs"; 4 | 5 | (async function() { 6 | const pkgDir = `${__dirname}/../packages`; 7 | const folderSrc = new PackagesFolderSource(pkgDir); 8 | const allPkgs = await folderSrc.getAllCached(); 9 | const bundleJson = JSON.stringify(allPkgs, null, 4); 10 | writeFileSync(`${pkgDir}/bundle.json`, bundleJson); 11 | })(); -------------------------------------------------------------------------------- /build/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "baseUrl": "../", 4 | "paths": { 5 | "@one/*": ["src/*"] 6 | }, 7 | "target": "es2020", 8 | "module": "umd", 9 | "moduleResolution": "node", 10 | "sourceMap": true, 11 | }, 12 | "include": ["*.ts"], 13 | "references": [ 14 | { "path": "../" } 15 | ] 16 | } -------------------------------------------------------------------------------- /docs/expression-language.md: -------------------------------------------------------------------------------- 1 | # ExprLang (expression language) 2 | 3 | ## Implementation 4 | 5 | Source: `src/Generator/ExprLang/` 6 | 7 | ## Description 8 | 9 | The OneLang expression language can parse expressions like 10 | ```javascript 11 | !arr[5].method(1 + 3 * 6, "string") && name != 'waldo' 12 | ``` 13 | and evaluates it over a model, calculating the expression's value. 14 | 15 | It has the following parts: 16 | 17 | * [Tokenizer (lexer)](exprlang-lexer.md) 18 | * [AST (Abstract Syntax Tree)](exprlang-ast.md) 19 | * [Parser](exprlang-parser.md) 20 | 21 | -------------------------------------------------------------------------------- /docs/exprlang-ast.md: -------------------------------------------------------------------------------- 1 | # AST (Abstract Syntax Tree) 2 | 3 | ## Implementation 4 | 5 | Source: `src/Generator/ExprLang/ExprLangAst.ts` 6 | 7 | ## Usage 8 | 9 | See the [Parser documentation](exprlang-parser.md) for usage information. 10 | 11 | ## Description 12 | 13 | The ExprLang expressions can be represented as an [Abstract Syntax Tree](https://en.wikipedia.org/wiki/Abstract_syntax_tree). 14 | 15 | ExprLang supports the following AST nodes (called expressions, e.g. `BinaryExpression`): 16 | 17 | * Binary: 18 | * format: ` ` 19 | * operators: `"+"` (addition), `"-"` (subtract), `"*"` (multiply), `"/"` (division), `"<<"` (left shift), `">>"` (right shift) 20 | * example: `len - 1` where `left` is `len`, `op` is `-`, `right` is `1` 21 | * Unary: 22 | * format: ` ` 23 | * operators: `"+"` (positive), `"-"` (negative), `"!"` (not, negate) 24 | * example: `-position` where `op` is `-`, `expr` is `position` 25 | * Literal: 26 | * format: has a type (number, string or boolean) and a value of that type 27 | * value examples: `1234` (number), `"hello"` (string), `true` (boolean) 28 | * Identifier: 29 | * format: an identifier 30 | * example: `varName` 31 | * Parenthesized: 32 | * format: `()` 33 | * example: `(1+2)` where `expr` is `1+2` 34 | * Conditional: 35 | * format: ` ? : ` 36 | * example: `varName ? 1 : 2` where `condition` is `varName`, `whenTrue` is `1`, `whenFalse` is `2` 37 | * Call: 38 | * format: `(, arguments[1], ...)` 39 | * example: `checkAccess(user, request.password, "adminRole")` where `method` is `checkAccess`, and `arguments` is an array of the following expressions: `user`, `request.password`, `"adminRole"` 40 | * PropertyAccess: 41 | * format: `.` 42 | * example: `request.password` where `object` is `request` and `propertyName` is `password` 43 | * ElementAccess: 44 | * format: `[]` 45 | * example: `user.items[len - 1]` where `object` is `user.items` and `elementExpr` is `len - 1` -------------------------------------------------------------------------------- /docs/exprlang-parser.md: -------------------------------------------------------------------------------- 1 | # Expression language: Parser 2 | 3 | ## Implementation 4 | 5 | Source: `src/Generator/ExprLang/ExprLangParser.ts` 6 | 7 | ## Tests 8 | 9 | Source: `test/src/TemplateTest.ts` // `runExpressionTests` and `runExpressionAstTests` methods 10 | 11 | Test cases: `test/src/TemplateTest.yaml` // `expressionTests` and `expressionAstTests` nodes 12 | 13 | ## Example usage 14 | 15 | Code 16 | 17 | ```javascript 18 | import { ExprLangParser, ExprLangAst } from "onelang"; 19 | 20 | const expr: ExprLangAst.Expression = ExprLangParser.parse("1+2*3"); 21 | console.log(expr); 22 | ``` 23 | 24 | Result 25 | 26 | ```javascript 27 | { kind: 'binary', 28 | op: '+', 29 | left: { kind: 'literal', type: 'number', value: 1 }, 30 | right: 31 | { kind: 'binary', 32 | op: '*', 33 | left: { kind: 'literal', type: 'number', value: 2 }, 34 | right: { kind: 'literal', type: 'number', value: 3 } } } 35 | ``` 36 | 37 | Code 38 | 39 | ```javascript 40 | console.log(ExprLangAstPrinter.print(expr)); 41 | ``` 42 | 43 | Result 44 | 45 | ```javascript 46 | (1 + (2 * 3)) 47 | ``` 48 | 49 | ## Description 50 | 51 | ExprLang parser is a modified [Pratt parser based on this article](https://journal.stuffwithstuff.com/2011/03/19/pratt-parsers-expression-parsing-made-easy/). It uses the [tokenizer](exprlang-lexer.md) and builds an [ExprLang AST](exprlang-ast.md) from an ExprLang expression. 52 | 53 | The `precedenceLevels` variable tells the parser which operator has precedence over which others. For example `product` (`*`, `/`) is later in the list meaning that it's "stronger" than `sum` (`+`, `-`), so the expression `1 + 2 * 3` will be converted to `1 + (2 * 3)` not to `(1 + 2) * 3`. -------------------------------------------------------------------------------- /docs/onelang-ast.md: -------------------------------------------------------------------------------- 1 | | Node type | Name | Type | Init | Lead.
Trivia,
Attrs | Visib.,
Static | Params,
Body,
Throws | Type
Args | Met-
hods,
Base
intf. | Imp
ort
able | Base
Class,
Constr.,
Fields,
Props
| Getter,
Setter | Parent | 2 | |-----------------|:--:|:--:|:--:|:---:|:--:|:--:|:---:|:--:|:--:|:--:|:--:|:---:| 3 | | Import | ❌ | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | 4 | | Enum | ✅ | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | ❌ | ✅ | ❌ | ❌ | ✅ | 5 | | EnumMember | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | 6 | | Interface | ✅ | ❌ | ❌ | ✅ | ❌ | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | ✅ | 7 | | Class | ✅ | ❌ | ❌ | ✅ | ❌ | ❌ | ✅ | ✅ | ✅ | ✅ | ❌ | ✅ | 8 | | IMethodBase | ❌ | ❌ | ❌ | ✅ | ❌ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | 9 | | Constructor | ❌ | ❌ | ❌ | ✅ | ❌ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | 10 | | Method | ✅ | ❌ | ❌ | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ | ✅ | 11 | | MethodParameter | ✅ | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | 12 | | Field | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | 13 | | Property | ✅ | ✅ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | 14 | | SourceFile | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | 15 | -------------------------------------------------------------------------------- /docs/onelang-project-structure.md: -------------------------------------------------------------------------------- 1 | # OneLang (core library) project structure 2 | 3 | ## Directory structure 4 | 5 | * documentation (`docs/`) 6 | * source code of OneLang - TypeScript code (`src/`) 7 | * compiled code of OneLang - JavaScript code (`lib/`) 8 | * source code parsing (`src/Parsers/`) 9 | * intermediate code model, AST (`src/One/`) 10 | * code transformations (`src/One/Transforms/`) 11 | * target code generator (`src/Generator/`) 12 | * [ExprLang: expression language](expression-language.md) (`src/Generator/ExprLang/`) 13 | * OneTemplate: templating engine (`src/Generator/OneTemplate/`) 14 | * package handling (`src/StdLib/`) 15 | * standard library packages (`packages/`) 16 | * OneLang interface declarations (`packages/interfaces/`) 17 | * metadata in `.yaml` files 18 | * declarations in TypeScript declaration `.d.ts` files 19 | * native implementations which are written in target languages (`packages/implementations/`) 20 | * target language definition templates (`langs/`) 21 | * tests (`test/`) 22 | * source code of the testing program (`test/src/`) 23 | * test inputs (`test/input/.ts`) 24 | * source code which compiled to other languages (and stored in the `artifacts` subfolder) 25 | * test artifacts (`test/artifacts//`) 26 | * compiled codes and exported intermediate model stages to diff changes 27 | * submodule to `TestArtifacts` repository 28 | 29 | Source files in the `src/` directory are written in TypeScript and compiled into JavaScript (`lib/` folder) via `tsc` (TypeScript compiler) using the `tsconfig.json` TypeScript configuration file. 30 | 31 | -------------------------------------------------------------------------------- /docs/transformations.md: -------------------------------------------------------------------------------- 1 | # Transformations 2 | 3 | ## FillParent 4 | 5 | Dependencies: - 6 | 7 | ## FillAttributesFromTrivia 8 | 9 | Dependencies: - 10 | 11 | ## ResolveImports 12 | 13 | ### Dependencies 14 | 15 | * FillAttributesFromTrivia 16 | * in case of importing logic depends on attributes (not used currently) -------------------------------------------------------------------------------- /langs/NativeResolvers/php.ts: -------------------------------------------------------------------------------- 1 | class PhpArray { 2 | _one: OneArray; 3 | 4 | get length(): OneNumber { return this._one.length; } 5 | add(item: T): void { this._one.add(item); } 6 | } 7 | 8 | class PhpMap { 9 | _one: OneMap; 10 | } 11 | 12 | class PhpString { 13 | _one: OneString; 14 | } 15 | 16 | class PhpBoolean { 17 | _one: OneBoolean; 18 | } 19 | 20 | class PhpNumber { 21 | _one: OneNumber; 22 | } -------------------------------------------------------------------------------- /langs/NativeResolvers/ruby.ts: -------------------------------------------------------------------------------- 1 | class RubyArray { 2 | _one: OneArray; 3 | 4 | get length(): number { return this._one.length; } 5 | 6 | get(index: number): T { 7 | return this._one.get(index); 8 | } 9 | 10 | set(index: number, value: T) { 11 | return this._one.set(index, value); 12 | } 13 | } 14 | 15 | class RubyMap { 16 | _one: OneMap; 17 | 18 | get(key: K): V { 19 | return this._one.get(key); 20 | } 21 | 22 | set(key: K, value: V) { 23 | this._one.set(key, value); 24 | } 25 | 26 | keys(): K[] { return this._one.keys(); } 27 | values(): V[] { return this._one.values(); } 28 | } 29 | 30 | class RubyString { 31 | _one: OneString; 32 | 33 | get length(): OneNumber { return this._one.length; } 34 | 35 | get(idx: number): OneCharacter { 36 | return this._one.get(idx); 37 | } 38 | } 39 | 40 | class RubyBoolean { 41 | _one: OneBoolean; 42 | } 43 | 44 | class RubyNumber { 45 | _one: OneNumber; 46 | } 47 | 48 | class IO { 49 | static read(filename: string): OneString { 50 | return OneFile.readText(filename); 51 | } 52 | } -------------------------------------------------------------------------------- /lib/.npmignore: -------------------------------------------------------------------------------- 1 | # ignore e.g. .npmignore 2 | \.* 3 | *.js.map -------------------------------------------------------------------------------- /onepkg/One.Ast-v0.1/index.d.ts: -------------------------------------------------------------------------------- 1 | export declare interface IType { 2 | repr(): string; 3 | } -------------------------------------------------------------------------------- /onepkg/One.Core-v0.1/index.d.ts: -------------------------------------------------------------------------------- 1 | export declare class One { 2 | static langName(); 3 | } -------------------------------------------------------------------------------- /onepkg/One.Core-v0.1/index.js: -------------------------------------------------------------------------------- 1 | class One { 2 | static langName() { return "TypeScript"; } 3 | } 4 | 5 | exports.One = One; -------------------------------------------------------------------------------- /onepkg/One.File-v0.1/index.d.ts: -------------------------------------------------------------------------------- 1 | export class OneFile { 2 | static readText(fn: string): string; 3 | static writeText(fn: string, content: string): void; 4 | static listFiles(dir: string, recursive: boolean): string[]; 5 | static copy(srcFn: string, dstFn: string): void; 6 | } -------------------------------------------------------------------------------- /onepkg/One.File-v0.1/index.js: -------------------------------------------------------------------------------- 1 | const glob = require('glob'); 2 | const fs = require('fs'); 3 | const path = require('path'); 4 | 5 | class OneFile { 6 | static readText(fn) { 7 | return fs.readFileSync(fn, 'utf8'); 8 | } 9 | 10 | static providePath(fn) { 11 | const dir = path.dirname(fn); 12 | if (!fs.existsSync(dir)) 13 | fs.mkdirSync(dir, { recursive: true }); 14 | return fn; 15 | } 16 | 17 | static writeText(fn, content) { 18 | return fs.writeFileSync(this.providePath(fn), content, 'utf8'); 19 | } 20 | 21 | static listFiles(dir, recursive) { 22 | if (!recursive) 23 | throw new Error("Not supported!"); 24 | const files = glob.sync("**/*", { cwd: dir, nodir: true, dot: true }); 25 | files.sort(); 26 | return files; 27 | } 28 | 29 | static copy(srcFn, dstFn) { 30 | fs.copyFileSync(srcFn, this.providePath(dstFn)); 31 | } 32 | } 33 | 34 | exports.OneFile = OneFile; -------------------------------------------------------------------------------- /onepkg/One.Json-v0.1/index.d.ts: -------------------------------------------------------------------------------- 1 | export declare class OneJProperty { 2 | getName(): string; 3 | getValue(obj: OneJValue): OneJValue; 4 | } 5 | 6 | export declare class OneJObject { 7 | //getProperties(): OneJProperty[]; 8 | names(): string[]; 9 | get(name: string): OneJValue; 10 | } 11 | 12 | export declare class OneJValue { 13 | isObject(): boolean; 14 | isArray(): boolean; 15 | isString(): boolean; 16 | isNumber(): boolean; 17 | isBool(): boolean; 18 | isNull(): boolean; 19 | 20 | asString(): string; 21 | asNumber(): number; 22 | asBool(): boolean; 23 | asObject(): OneJObject; 24 | 25 | getArrayItems(): OneJValue[]; 26 | } 27 | 28 | export declare class OneJson { 29 | static parse(str: string): OneJValue; 30 | static serializeFormatted(obj: any): string; 31 | } 32 | -------------------------------------------------------------------------------- /onepkg/One.Json-v0.1/index.js: -------------------------------------------------------------------------------- 1 | class OneJObject { 2 | constructor(value) { this.value = value; } 3 | 4 | names() { return Object.keys(this.value); } 5 | get(name) { return new OneJValue(this.value[name]); } 6 | } 7 | 8 | class OneJValue { 9 | constructor(value) { this.value = value; } 10 | 11 | isObject() { return typeof this.value === "object" && !Array.isArray(this.value); } 12 | isArray() { return Array.isArray(this.value); } 13 | isString() { return typeof this.value === "string"; } 14 | isNumber() { return typeof this.value === "number"; } 15 | isBool() { return typeof this.value === "boolean"; } 16 | isNull() { return this.value === null; } 17 | 18 | asString() { return this.value; } 19 | asNumber() { return this.value; } 20 | asBool() { return this.value; } 21 | asObject() { return new OneJObject(this.value); } 22 | 23 | getArrayItems() { return this.value.map(x => new OneJValue(x)); } 24 | } 25 | 26 | class OneJson { 27 | static parse(content) { 28 | return new OneJValue(JSON.parse(content)); 29 | } 30 | 31 | static serializeFormatted(obj) { return JSON.stringify(obj, null, 4); } 32 | } 33 | 34 | exports.OneJson = OneJson; -------------------------------------------------------------------------------- /onepkg/One.Reflect-v0.1/index.d.ts: -------------------------------------------------------------------------------- 1 | import { IType } from "One.Ast-v0.1"; 2 | 3 | export declare class ReflectedValue { 4 | getField(name: string): ReflectedValue; 5 | getArrayItems(): ReflectedValue[]; 6 | getMapKeys(): string[]; 7 | getMapValue(key: string): ReflectedValue; 8 | getEnumValueAsString(): string; 9 | getBooleanValue(): boolean; 10 | getStringValue(): string; 11 | isNull(): boolean; 12 | getUniqueIdentifier(): any; 13 | getValueType(): IType; 14 | getDeclaredType(): IType; 15 | } 16 | 17 | export declare class Reflection { 18 | static registerClass(cls: any, type: IType); 19 | static getClassType(cls: any); 20 | static wrap(value: any, declaredType: IType); 21 | } -------------------------------------------------------------------------------- /onepkg/One.Reflect-v0.1/index.js: -------------------------------------------------------------------------------- 1 | class ReflectedValue { 2 | constructor(value, declaredType) { 3 | this.value = value; 4 | this.declaredType = declaredType; 5 | } 6 | 7 | getField(name) { 8 | return new ReflectedValue(this.value[name], this.declaredType.decl.fields.find(x => x.name === name).type); 9 | } 10 | 11 | getArrayItems() { 12 | return this.value.map(x => new ReflectedValue(x, this.declaredType.typeArguments[0])); 13 | } 14 | 15 | getMapKeys() { 16 | return Object.keys(this.value); 17 | } 18 | 19 | getMapValue(name) { 20 | return new ReflectedValue(this.value[name], this.declaredType.typeArguments[0]); 21 | } 22 | 23 | getEnumValueAsString() { 24 | return this.declaredType.decl.values[this.value].name; 25 | } 26 | 27 | getBooleanValue() { return this.value; } 28 | getStringValue() { return this.value; } 29 | isNull() { return this.value === null; } 30 | getUniqueIdentifier() { return this.value; } 31 | 32 | getDeclaredType() { return this.declaredType; } 33 | getValueType() { 34 | if (typeof this.valueType === "undefined") 35 | this.valueType = typeof value === "object" ? Reflection.getClassType(value.__proto__.constructor) : null 36 | return this.valueType; 37 | } 38 | } 39 | 40 | class Reflection { 41 | static registerClass(cls, type) { this.classTypes[cls] = type; } 42 | 43 | static getClassType(cls) { 44 | if (!(cls in this.classTypes)) 45 | throw new Error(`Class was not registered for Reflection: ${cls.name}`); 46 | 47 | return this.classTypes[cls]; 48 | } 49 | 50 | static wrap(value, declaredType) { return new ReflectedValue(value, declaredType); } 51 | } 52 | Reflection.classTypes = {}; 53 | 54 | exports.ReflectedValue = ReflectedValue; 55 | exports.Reflection = Reflection; 56 | -------------------------------------------------------------------------------- /onepkg/One.Yaml-v0.1/index.d.ts: -------------------------------------------------------------------------------- 1 | export declare enum ValueType { Null = 0, Boolean = 1, Number = 2, String = 3, Array = 4, Object = 5 } 2 | 3 | export declare class YamlValue { 4 | type(): ValueType; 5 | asStr(): string; 6 | 7 | obj(key: string): YamlValue; 8 | dbl(key: string): number; 9 | str(key: string): string; 10 | arr(key: string): YamlValue[]; 11 | dict(key: string): { [name: string]: YamlValue }; 12 | strArr(key: string): string[]; 13 | } 14 | 15 | export declare class OneYaml { 16 | static load(content: string): YamlValue; 17 | } -------------------------------------------------------------------------------- /onepkg/One.Yaml-v0.1/index.js: -------------------------------------------------------------------------------- 1 | const YAML = require('js-yaml'); 2 | 3 | const ValueType = { Null: 0, Boolean: 1, Number: 2, String: 3, Array: 4, Object: 5 }; 4 | 5 | class YamlValue { 6 | constructor(value) { this.value = value; } 7 | 8 | type() { 9 | const t = typeof(this.value); 10 | return this.value === null ? 0 : 11 | t === "boolean" ? 1 : 12 | t === "number" ? 2 : 13 | t === "string" ? 3 : 14 | Array.isArray(this.value) ? 4 : 5; } 15 | asStr() { return this.value; } 16 | 17 | obj(key) { return new YamlValue(this.value[key]); } 18 | dbl(key) { return this.value[key] || 0; } 19 | str(key) { return this.value[key] || null; } 20 | arr(key) { return (this.value[key] || []).map(x => new YamlValue(x)); } 21 | dict(key) { return Object.fromEntries(Object.entries(this.value[key] || {}).map(([key,value]) => [key, new YamlValue(value)])); } 22 | strArr(key) { return this.value[key] || []; } 23 | } 24 | 25 | class OneYaml { 26 | static load(content) { 27 | return new YamlValue(YAML.safeLoad(content)); 28 | } 29 | } 30 | 31 | exports.ValueType = ValueType; 32 | exports.YamlValue = YamlValue; 33 | exports.OneYaml = OneYaml; -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "onelang", 3 | "version": "0.0.7", 4 | "description": "OneLang transpiler framework core", 5 | "main": "./lib/index.js", 6 | "types": "./lib/index.d.ts", 7 | "license": "MIT", 8 | "author": { 9 | "name": "Koczka Tamás", 10 | "email": "koczkatamas@gmail.com", 11 | "url": "https://kt.gy/" 12 | }, 13 | "repository": { 14 | "type": "git", 15 | "url": "git+https://github.com/onelang/OneLang.git" 16 | }, 17 | "keywords": [ 18 | "onelang", 19 | "transpiler", 20 | "source-to-source", 21 | "programming-language" 22 | ], 23 | "bugs": { 24 | "url": "https://github.com/onelang/OneLang/issues" 25 | }, 26 | "homepage": "https://onelang.io", 27 | "files": [ 28 | "langs", 29 | "lib", 30 | "packages" 31 | ], 32 | "directories": {}, 33 | "scripts": { 34 | "build": "tsc -b . build", 35 | "pretest": "tsc -b . test", 36 | "test": "npx mocha", 37 | "bundle": "node build/bundle-packages.js", 38 | "prepublishOnly": "npm run build", 39 | "release": "release-it" 40 | }, 41 | "dependencies": { 42 | "js-yaml": "^3.13.1" 43 | }, 44 | "devDependencies": { 45 | "@types/ansi-colors": "^3.2.2", 46 | "@types/chai": "^4.2.8", 47 | "@types/diff": "^4.0.2", 48 | "@types/js-yaml": "^3.12.2", 49 | "@types/mocha": "^7.0.1", 50 | "@types/node": "^14.14.10", 51 | "diff": "^4.0.2", 52 | "mkdirp": "^1.0.4", 53 | "mocha": "^7.2.0", 54 | "module-alias": "^2.2.2", 55 | "release-it": "^14.0.2", 56 | "request": "^2.88.0", 57 | "ts-node": "^8.10.2", 58 | "tsconfig-paths": "^3.9.0", 59 | "typescript": "^3.7.5" 60 | }, 61 | "_moduleAliases": { 62 | "@one": "lib" 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-Console-v0.1/Java/JsToJava.yaml: -------------------------------------------------------------------------------- 1 | expressions: 2 | console.log(obj): System.out.println($obj) 3 | console.error(obj): System.err.println($obj) -------------------------------------------------------------------------------- /packages/implementations/OneLang-Core-v0.1/CSharp/JsToCSharp.yaml: -------------------------------------------------------------------------------- 1 | expressions: 2 | One.langName(): '"CSharp"' 3 | Error.message: $this.ToString() -------------------------------------------------------------------------------- /packages/implementations/OneLang-Core-v0.1/CSharp/src/Array.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | 4 | public static class Array { 5 | public static T[] from(IEnumerable obj) { 6 | return obj.ToArray(); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-Core-v0.1/CSharp/src/Error.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class Error : Exception { 4 | public Error() { } 5 | public Error(string msg): base(msg) { } 6 | public static int stackTraceLimit = 0; 7 | public string stack; 8 | } 9 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-Core-v0.1/CSharp/src/Global.cs: -------------------------------------------------------------------------------- 1 | public static class Global { 2 | public static int parseInt(string str) { 3 | return int.Parse(str); 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-Core-v0.1/CSharp/src/Map.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | 4 | public class Map { 5 | Dictionary items = new Dictionary(); 6 | 7 | public TValue get(TKey key) 8 | { 9 | return items.GetValueOrDefault(key); 10 | } 11 | 12 | public void set(TKey key, TValue value) 13 | { 14 | items[key] = value; 15 | } 16 | 17 | public void delete(TKey key) 18 | { 19 | items.Remove(key); 20 | } 21 | 22 | public bool has(TKey key) 23 | { 24 | return items.ContainsKey(key); 25 | } 26 | 27 | public TValue[] values() 28 | { 29 | return items.Values.ToArray(); 30 | } 31 | 32 | public int size() 33 | { 34 | return items.Count; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-Core-v0.1/CSharp/src/Math.cs: -------------------------------------------------------------------------------- 1 | public static class Math { 2 | public static int floor(int num) { 3 | return num; 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-Core-v0.1/CSharp/src/Object.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Linq; 3 | 4 | public static class Object { 5 | public static string[] keys(Dictionary dict) { 6 | return dict.Select(x => x.Key).ToArray(); 7 | } 8 | 9 | public static TValue[] values(Dictionary dict) { 10 | return dict.Select(x => x.Value).ToArray(); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-Core-v0.1/CSharp/src/Promise.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | 3 | public class Promise { 4 | public static Task resolve(T value) { 5 | return Task.FromResult(value); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-Core-v0.1/CSharp/src/RegExp.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using System.Text.RegularExpressions; 3 | 4 | public class RegExp { 5 | public string pattern; 6 | public string modifiers; 7 | public int lastIndex; 8 | public Match lastMatch; 9 | 10 | public RegExp(string pattern): this(pattern, null) { } 11 | 12 | public RegExp(string pattern, string modifiers) { 13 | this.pattern = pattern; 14 | this.modifiers = modifiers; 15 | } 16 | 17 | public string[] exec(string data) { 18 | this.lastMatch = this.lastMatch == null ? new Regex($"\\G(?:{this.pattern})").Match(data, this.lastIndex) : lastMatch.NextMatch(); 19 | return this.lastMatch.Success ? this.lastMatch.Groups.Cast().Select(x => x.Value).ToArray() : null; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-Core-v0.1/CSharp/src/Set.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | 5 | public class Set: IEnumerable 6 | { 7 | HashSet items; 8 | 9 | public Set() { 10 | items = new HashSet(); 11 | } 12 | 13 | public Set(IEnumerable items) { 14 | this.items = new HashSet(items); 15 | } 16 | 17 | public void add(T item) { 18 | items.Add(item); 19 | } 20 | 21 | public T[] values() { 22 | return items.ToArray(); 23 | } 24 | 25 | IEnumerator IEnumerable.GetEnumerator() 26 | { 27 | return items.GetEnumerator(); 28 | } 29 | 30 | public IEnumerator GetEnumerator() 31 | { 32 | return items.GetEnumerator(); 33 | } 34 | 35 | internal bool has(T item) 36 | { 37 | return this.items.Contains(item); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-Core-v0.1/CSharp/src/console.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public static class console { 4 | public static void log(string msg) { 5 | Console.WriteLine(msg); 6 | } 7 | 8 | public static void error(string msg) { 9 | var oldColor = Console.ForegroundColor; 10 | Console.ForegroundColor = ConsoleColor.Red; 11 | Console.WriteLine(msg); 12 | Console.ForegroundColor = oldColor; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-Core-v0.1/Java/src/ExceptionHelper.java: -------------------------------------------------------------------------------- 1 | package io.onelang.std.core; 2 | 3 | import java.io.StringWriter; 4 | import java.io.PrintWriter; 5 | 6 | public class ExceptionHelper { 7 | public static String toString(Exception e) { 8 | StringWriter sw = new StringWriter(); 9 | e.printStackTrace(new PrintWriter(sw)); 10 | return sw.toString(); 11 | } 12 | } 13 | 14 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-Core-v0.1/Java/src/Objects.java: -------------------------------------------------------------------------------- 1 | package io.onelang.std.core; 2 | 3 | public class Objects { 4 | public static boolean equals(Object o1, Object o2) { 5 | return o1 == o2 || (o1 != null && o1.equals(o2)); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-Core-v0.1/Java/src/One.java: -------------------------------------------------------------------------------- 1 | package io.onelang.std.core; 2 | 3 | public class One { 4 | } -------------------------------------------------------------------------------- /packages/implementations/OneLang-Core-v0.1/Java/src/RegExp.java: -------------------------------------------------------------------------------- 1 | package io.onelang.std.core; 2 | 3 | import java.util.regex.Matcher; 4 | import java.util.regex.Pattern; 5 | 6 | public class RegExp { 7 | String pattern; 8 | String modifiers; 9 | public Integer lastIndex; 10 | 11 | public RegExp(String pattern) { this(pattern, null); } 12 | public RegExp(String pattern, String modifiers) { 13 | this.lastIndex = 0; 14 | this.pattern = pattern; 15 | this.modifiers = modifiers; 16 | } 17 | 18 | public String[] exec(String data) { 19 | //System.out.println("matching '" + data.substring(this.lastIndex, Math.min(this.lastIndex + 30, data.length())).replace("\n", "\\n") + "' with pattern '" + this.pattern + "' from index " + this.lastIndex); 20 | var pattern = Pattern.compile("\\G(?:" + this.pattern + ")"); 21 | var matcher = pattern.matcher(data); 22 | if (!matcher.find(this.lastIndex)) return null; 23 | this.lastIndex = matcher.end(); 24 | var result = new String[matcher.groupCount() + 1]; 25 | for (int i = 0; i <= matcher.groupCount(); i++) 26 | result[i] = matcher.group(i); 27 | //System.out.println(" => found match: '" + result[0] + "'"); 28 | return result; 29 | } 30 | } -------------------------------------------------------------------------------- /packages/implementations/OneLang-Core-v0.1/Java/src/StdArrayHelper.java: -------------------------------------------------------------------------------- 1 | package io.onelang.std.core; 2 | 3 | import java.util.function.BiFunction; 4 | import java.util.List; 5 | import java.util.ArrayList; 6 | 7 | public class StdArrayHelper { 8 | public static Boolean allMatch(T[] items, BiFunction predicate) { 9 | int idx = 0; 10 | for (T item : items) 11 | if (!predicate.apply(item, idx++)) 12 | return false; 13 | return true; 14 | } 15 | 16 | public static Boolean allMatch(List items, BiFunction predicate) { 17 | int idx = 0; 18 | for (T item : items) 19 | if (!predicate.apply(item, idx++)) 20 | return false; 21 | return true; 22 | } 23 | } -------------------------------------------------------------------------------- /packages/implementations/OneLang-Core-v0.1/Java/src/console.java: -------------------------------------------------------------------------------- 1 | package io.onelang.std.core; 2 | 3 | public class console { 4 | public static void log(String data) { 5 | System.out.println(data); 6 | } 7 | 8 | public static void error(String data) { 9 | System.err.println(data); 10 | } 11 | } -------------------------------------------------------------------------------- /packages/implementations/OneLang-Core-v0.1/PHP/src/ArrayHelper.php: -------------------------------------------------------------------------------- 1 | $item) 20 | if (!$func($item, $i)) 21 | return false; 22 | return true; 23 | } 24 | 25 | static function some($arr, $func) { return self::find($arr, $func) !== null; } 26 | } 27 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-Core-v0.1/PHP/src/Array_.php: -------------------------------------------------------------------------------- 1 | arr); } 9 | function has($key) { return array_key_exists($key, $this->arr); } 10 | function get($key) { return $this->arr[$key] ?? null; } 11 | function set($key, $value) { $this->arr[$key] = $value; } 12 | function delete($key) { unset($this->arr[$key]); } 13 | } 14 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-Core-v0.1/PHP/src/RegExp.php: -------------------------------------------------------------------------------- 1 | regex = "/$pattern/A"; 13 | } 14 | 15 | function exec($input) { 16 | //print("preg_match, pattern='{$this->regex}', offset={$this->lastIndex}, input='" . str_replace("\n", "\\n", substr($input, $this->lastIndex, 30)) . "'\n"); 17 | if (preg_match($this->regex, $input, $matches, PREG_OFFSET_CAPTURE, $this->lastIndex) === 0) 18 | return null; 19 | 20 | //var_dump($matches); 21 | $this->lastIndex = $matches[0][1] + strlen($matches[0][0]); 22 | //print("new offset={$this->lastIndex}\n"); 23 | $result = array_map(function($x){ return $x[0]; }, $matches); 24 | //var_dump($result); 25 | return $result; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-Core-v0.1/PHP/src/Set.php: -------------------------------------------------------------------------------- 1 | add($item); 11 | } 12 | 13 | function values() { return array_values($this->arr); } 14 | function has($item) { return in_array($item, $this->arr); } 15 | function add($item) { if(!$this->has($item)) $this->arr[] = $item; } 16 | } -------------------------------------------------------------------------------- /packages/implementations/OneLang-Core-v0.1/PHP/src/console.php: -------------------------------------------------------------------------------- 1 | {{gen(prop.initializer)}}, 45 | {{/for}} 46 | } 47 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-Core-v0.1/langs/typescript.yaml: -------------------------------------------------------------------------------- 1 | implements: 2 | - interface: { name: One.Core, minver: 0.1, maxver: 0.1 } 3 | language: typescript 4 | implementation: 5 | classes: 6 | OneString: 7 | type: string 8 | fields: 9 | length: "{{self}}.length" 10 | methods: 11 | substring: "{{self}}.substring({{start}}, {{end}})" 12 | split: "{{self}}.split({{separator}})" 13 | get: "{{self}}[{{idx}}]" 14 | replace: "{{self}}.split({{from}}).join({{to}})" 15 | substrMatch: "{{self}}.startsWith({{str}}, {{offset}})" 16 | OneNumber: 17 | type: number 18 | OneBoolean: 19 | type: bool 20 | OneArray: 21 | fields: 22 | length: "{{self}}.length" 23 | methods: 24 | add: "{{self}}.push({{item}})" 25 | get: "{{self}}[{{index}}]" 26 | set: "{{self}}[{{index}}] = {{value}}" 27 | OneMap: 28 | methods: 29 | keys: "Object.keys({{self}})" 30 | values: "Object.values({{self}})" 31 | remove: "delete {{self}}[{{key}}]" 32 | hasKey: "{{key}} in {{self}}" 33 | get: "{{self}}[{{key}}]" 34 | set: "{{self}}[{{key}}] = {{value}}" 35 | OneError: 36 | methods: 37 | raise: throw new Error({{message}}) 38 | One: 39 | methods: 40 | langName: '"TypeScript"' 41 | expressions: 42 | arrayLiteral: "[{{genParams(expr.items)}}]" 43 | mapLiteral: |- 44 | { 45 | {{for prop in expr.properties|sep=",\n"}} 46 | {{prop.name}}: {{gen(prop.initializer)}} 47 | {{/for}} 48 | } 49 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-Core-v0.1/native/one.go: -------------------------------------------------------------------------------- 1 | package one 2 | 3 | import "math/big" 4 | 5 | func BI() *big.Int { 6 | return big.NewInt(0) 7 | } -------------------------------------------------------------------------------- /packages/implementations/OneLang-Core-v0.1/native/one.pl: -------------------------------------------------------------------------------- 1 | package One; 2 | 3 | sub str_replace 4 | { 5 | my ($string, $find, $replace) = @_; 6 | 7 | my $pos = index($string, $find); 8 | 9 | while($pos > -1) { 10 | substr($string, $pos, length($find), $replace); 11 | $pos = index($string, $find, $pos + length($replace)); 12 | } 13 | 14 | return $string; 15 | } 16 | 17 | 1; -------------------------------------------------------------------------------- /packages/implementations/OneLang-Core-v0.1/native/one.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | 3 | public enum OneError : Error { 4 | case RuntimeError(String) 5 | } 6 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-Core-v0.1/package.yaml: -------------------------------------------------------------------------------- 1 | file-version: 1 2 | vendor: OneLang 3 | name: Core 4 | version: 0.1 5 | includes: 6 | - langs/cpp.yaml 7 | - langs/csharp.yaml 8 | - langs/go.yaml 9 | - langs/java.yaml 10 | - langs/javascript.yaml 11 | - langs/perl.yaml 12 | - langs/php.yaml 13 | - langs/python.yaml 14 | - langs/ruby.yaml 15 | - langs/swift.yaml 16 | - langs/typescript.yaml 17 | languages: 18 | php: 19 | native-src-dir: PHP/src 20 | generator-plugins: [PHP/JsToPhp.yaml] 21 | csharp: 22 | native-src-dir: CSharp/src 23 | generator-plugins: [CSharp/JsToCSharp.yaml] 24 | python: 25 | package-dir: onelang_core 26 | native-src-dir: Python/src 27 | generator-plugins: [Python/JsToPython.yaml] 28 | java: 29 | package-dir: core 30 | native-src-dir: Java/src 31 | generator-plugins: [Java/JsToJava.yaml] 32 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-File-v0.1/CPP/src/OneFile.cpp: -------------------------------------------------------------------------------- 1 | #include "OneFile.hpp" 2 | #include 3 | #include 4 | 5 | std::string OneFile::readText(const std::string& path) 6 | { 7 | std::ifstream file(path); 8 | std::string content((std::istreambuf_iterator(file)), std::istreambuf_iterator()); 9 | return content; 10 | } 11 | 12 | void OneFile::writeText(const std::string& path, const std::string& content) 13 | { 14 | std::ofstream file(path); 15 | file << content; 16 | } 17 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-File-v0.1/CPP/src/OneFile.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | class OneFile { 6 | public: 7 | static std::string readText(const std::string& path); 8 | static void writeText(const std::string& path, const std::string& content); 9 | }; 10 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-File-v0.1/CSharp/src/OneFile.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | using System.Linq; 4 | 5 | public static class OneFile 6 | { 7 | public static string[] listFiles(string directory, bool recursive) { 8 | var skipLen = directory.Length + (directory.EndsWith("/") ? 0 : 1); 9 | return Directory.GetFiles(directory, "*", SearchOption.AllDirectories).Select(x => x.Substring(skipLen)).OrderBy(x => x, StringComparer.Ordinal).ToArray(); 10 | } 11 | 12 | public static string readText(string fn) { 13 | return File.ReadAllText(fn); 14 | } 15 | 16 | public static void writeText(string fn, string content) { 17 | new DirectoryInfo(Path.GetDirectoryName(fn)).Create(); 18 | File.WriteAllText(fn, content); 19 | } 20 | 21 | public static void copy(string srcFn, string dstFn) { 22 | new DirectoryInfo(Path.GetDirectoryName(dstFn)).Create(); 23 | File.Copy(srcFn, dstFn, true); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-File-v0.1/Java/src/OneFile.java: -------------------------------------------------------------------------------- 1 | package io.onelang.std.file; 2 | 3 | import java.nio.file.Files; 4 | import java.nio.file.Path; 5 | import java.nio.file.Paths; 6 | import java.io.IOException; 7 | import io.onelang.std.core.console; 8 | 9 | public class OneFile { 10 | public static String readText(String fileName) { 11 | try { 12 | return Files.readString(Path.of(fileName)); 13 | } catch(Exception e) { 14 | console.error("[ERROR] readText (fn = " + fileName + "): " + e); 15 | return null; 16 | } 17 | } 18 | 19 | public static String providePath(String fileName) throws IOException { 20 | Files.createDirectories(Paths.get(fileName).getParent()); 21 | return fileName; 22 | } 23 | 24 | public static void writeText(String fileName, String data) { 25 | try { 26 | Files.writeString(Path.of(OneFile.providePath(fileName)), data); 27 | } catch(Exception e) { 28 | console.error("[ERROR] writeText (fn = " + fileName + "): " + e); 29 | } 30 | } 31 | 32 | public static String[] listFiles(String directory, Boolean recursive) { 33 | try { 34 | final var dirLen = directory.length(); 35 | var files = Files.walk(Paths.get(directory)).filter(Files::isRegularFile).map(Path::toString).map(x -> x.substring(dirLen)).sorted().toArray(String[]::new); 36 | return files; 37 | } catch(Exception e) { 38 | console.error(e.toString()); 39 | return null; 40 | } 41 | } 42 | 43 | public static void copy(String srcFn, String dstFn) { 44 | try { 45 | Files.copy(Path.of(srcFn), Path.of(OneFile.providePath(dstFn))); 46 | } catch(Exception e) { 47 | console.error("[ERROR] copy (srcFn = " + srcFn + ", dstFn = " + dstFn + "): " + e); 48 | } 49 | } 50 | } -------------------------------------------------------------------------------- /packages/implementations/OneLang-File-v0.1/PHP/OneFile.yaml: -------------------------------------------------------------------------------- 1 | expressions: 2 | #OneFile.copy(src, dst): copy($src, $dst) 3 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-File-v0.1/PHP/src/OneFile.php: -------------------------------------------------------------------------------- 1 | isDir()) 17 | $files[] = substr($file->getPathname(), strlen($dir)); 18 | 19 | sort($files); 20 | return $files; 21 | } 22 | 23 | static function readText($fn) { 24 | return file_get_contents($fn); 25 | } 26 | 27 | static function providePath($fn) { 28 | $dir = dirname($fn); 29 | if (!file_exists($dir)) 30 | mkdir($dir, 0777, true); 31 | return $fn; 32 | } 33 | 34 | static function writeText($fn, $contents) { 35 | //print("writing file: $fn\n"); 36 | file_put_contents(OneFile::providePath($fn), $contents); 37 | } 38 | 39 | static function copy($src, $dst) { 40 | copy($src, OneFile::providePath($dst)); 41 | } 42 | } -------------------------------------------------------------------------------- /packages/implementations/OneLang-File-v0.1/Python/src/OneFile.py: -------------------------------------------------------------------------------- 1 | import pathlib 2 | import os 3 | import shutil 4 | 5 | class OneFile: 6 | def read_text(fn): 7 | with open(fn, newline='') as f: return f.read() 8 | 9 | def write_text(fn, content): 10 | os.makedirs(os.path.dirname(fn), exist_ok=True) 11 | with open(fn, 'w') as f: f.write(content) 12 | 13 | def list_files(dir, recursive): 14 | files = list(sorted([str(x.relative_to(dir)) for x in pathlib.Path(dir).glob("**/*") if x.is_file()])) 15 | return files 16 | 17 | def copy(src, dst): 18 | os.makedirs(os.path.dirname(dst), exist_ok=True) 19 | shutil.copy(src, dst) 20 | 21 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-File-v0.1/Python/src/__init__.py: -------------------------------------------------------------------------------- 1 | from .OneFile import * -------------------------------------------------------------------------------- /packages/implementations/OneLang-File-v0.1/langs/cpp.yaml: -------------------------------------------------------------------------------- 1 | implements: 2 | - interface: { name: One.File, minver: 0.1, maxver: 0.1 } 3 | language: cpp 4 | native-include-dir: "cpp" 5 | implementation: 6 | classes: 7 | OneFile: 8 | includes: ["OneLang-File-v0.1/OneFile.hpp"] -------------------------------------------------------------------------------- /packages/implementations/OneLang-File-v0.1/langs/csharp.yaml: -------------------------------------------------------------------------------- 1 | implements: 2 | - interface: { name: One.File, minver: 0.1, maxver: 0.1 } 3 | language: csharp 4 | implementation: 5 | classes: 6 | OneFile: 7 | includes: [System.IO] 8 | methods: 9 | readText: "File.ReadAllText({{fn}})" 10 | writeText: "File.WriteAllText({{fn}}, {{content}})" 11 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-File-v0.1/langs/go.yaml: -------------------------------------------------------------------------------- 1 | implements: 2 | - interface: { name: One.File, minver: 0.1, maxver: 0.1 } 3 | language: go 4 | implementation: 5 | classes: 6 | OneFile: 7 | includes: [io/ioutil] 8 | methods: 9 | readText: 10 | extraArgs: [result] 11 | template: |- 12 | {{result}}Bytes, _ := ioutil.ReadFile({{fn}}) 13 | {{result}} := string({{result}}Bytes) 14 | writeText: 15 | template: |- 16 | ioutil.WriteFile({{fn}}, []byte({{content}}), 0644) 17 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-File-v0.1/langs/java.yaml: -------------------------------------------------------------------------------- 1 | implements: 2 | - interface: { name: One.File, minver: 0.1, maxver: 0.1 } 3 | language: java 4 | implementation: 5 | classes: 6 | OneFile: 7 | methods: 8 | readText: 9 | includes: [java.nio.file.Paths, java.nio.file.Files] # java.io.IOException 10 | exceptions: [IOException] 11 | template: "new String(Files.readAllBytes(Paths.get({{fn}})));" 12 | writeText: 13 | includes: [java.nio.file.Paths, java.nio.file.Files] # java.io.IOException 14 | exceptions: [IOException] 15 | template: "Files.write(Paths.get({{fn}}), {{content}}.getBytes());" 16 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-File-v0.1/langs/javascript.yaml: -------------------------------------------------------------------------------- 1 | implements: 2 | - interface: { name: One.File, minver: 0.1, maxver: 0.1 } 3 | language: javascript 4 | implementation: 5 | classes: 6 | OneFile: 7 | includes: [fs] 8 | methods: 9 | readText: "fs.readFileSync({{fn}}, 'utf-8')" 10 | writeText: "fs.writeFileSync({{fn}}, {{content}})" 11 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-File-v0.1/langs/perl.yaml: -------------------------------------------------------------------------------- 1 | implements: 2 | - interface: { name: One.File, minver: 0.1, maxver: 0.1 } 3 | language: perl 4 | implementation: 5 | classes: 6 | OneFile: 7 | methods: 8 | readText: 9 | extraArgs: [result] 10 | template: |- 11 | open my $fh, '<', {{fn}} or die "Can't open file $!"; 12 | read $fh, my ${{result}}, -s $fh; 13 | close($fh); 14 | writeText: 15 | template: |- 16 | open my $fh2, '>', {{fn}} or die "Can't open file $!"; 17 | print $fh2, {{content}}, -s $fh2; 18 | close $fh2; 19 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-File-v0.1/langs/php.yaml: -------------------------------------------------------------------------------- 1 | implements: 2 | - interface: { name: One.File, minver: 0.1, maxver: 0.1 } 3 | language: php 4 | implementation: 5 | classes: 6 | OneFile: 7 | methods: 8 | readText: "file_get_contents({{fn}})" 9 | writeText: "file_put_contents({{fn}}, {{content}})" 10 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-File-v0.1/langs/python.yaml: -------------------------------------------------------------------------------- 1 | implements: 2 | - interface: { name: One.File, minver: 0.1, maxver: 0.1 } 3 | language: python 4 | implementation: 5 | classes: 6 | OneFile: 7 | methods: 8 | readText: 9 | extraArgs: [result] 10 | template: "with open({{fn}}, 'r') as f: {{result}} = f.read()" 11 | writeText: 12 | template: "with open({{fn}}, 'w') as f: f.write({{content}})" 13 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-File-v0.1/langs/ruby.yaml: -------------------------------------------------------------------------------- 1 | implements: 2 | - interface: { name: One.File, minver: 0.1, maxver: 0.1 } 3 | language: ruby 4 | implementation: 5 | classes: 6 | OneFile: 7 | methods: 8 | readText: "IO.read({{fn}})" 9 | writeText: "IO.write({{fn}}, {{content}})" 10 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-File-v0.1/langs/swift.yaml: -------------------------------------------------------------------------------- 1 | implements: 2 | - interface: { name: One.File, minver: 0.1, maxver: 0.1 } 3 | language: swift 4 | implementation: 5 | classes: 6 | OneFile: 7 | methods: 8 | readText: 9 | includes: [Foundation] 10 | template: "try! String(contentsOfFile: {{fn}}, encoding: String.Encoding.utf8)" 11 | writeText: 12 | includes: [Foundation] 13 | template: |- 14 | try! {{content}}.write(toFile: {{fn}}, atomically: false, encoding: .utf8) 15 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-File-v0.1/langs/typescript.yaml: -------------------------------------------------------------------------------- 1 | implements: 2 | - interface: { name: One.File, minver: 0.1, maxver: 0.1 } 3 | language: typescript 4 | implementation: 5 | classes: 6 | OneFile: 7 | includes: [fs] 8 | methods: 9 | readText: "fs.readFileSync({{fn}}, 'utf-8')" 10 | writeText: "fs.writeFileSync({{fn}}, {{content}})" 11 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-File-v0.1/package.yaml: -------------------------------------------------------------------------------- 1 | file-version: 1 2 | vendor: OneLang 3 | name: File 4 | version: 0.1 5 | includes: 6 | - langs/cpp.yaml 7 | - langs/csharp.yaml 8 | - langs/go.yaml 9 | - langs/java.yaml 10 | - langs/javascript.yaml 11 | - langs/perl.yaml 12 | - langs/php.yaml 13 | - langs/python.yaml 14 | - langs/ruby.yaml 15 | - langs/swift.yaml 16 | - langs/typescript.yaml 17 | languages: 18 | php: 19 | native-src-dir: PHP/src 20 | generator-plugins: [PHP/OneFile.yaml] 21 | csharp: 22 | native-src-dir: CSharp/src 23 | python: 24 | package-dir: onelang_file 25 | native-src-dir: Python/src 26 | java: 27 | package-dir: file 28 | native-src-dir: Java/src 29 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-Json-v0.1/CSharp/src/JSON.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | 3 | public static class JSON { 4 | public static string stringify(object obj) { 5 | return JsonConvert.SerializeObject(obj); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-Json-v0.1/CSharp/src/OneJson.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using Newtonsoft.Json.Linq; 3 | 4 | public static class OneJson { 5 | public static OneJValue parse(string content) { 6 | var value = JToken.Parse(content); 7 | return new OneJValue(value); 8 | } 9 | } 10 | 11 | public class OneJObject { 12 | public JObject value; 13 | public OneJObject(JObject value) { this.value = value; } 14 | 15 | public OneJValue get(string name) { return new OneJValue((JToken) this.value[name]); } 16 | } 17 | 18 | public class OneJValue { 19 | public JToken value; 20 | 21 | public OneJValue(JToken value) { this.value = value; } 22 | 23 | public string asString() { return (string)this.value; } 24 | public long asNumber() { return (long)this.value; } 25 | public bool asBool() { return (bool)this.value; } 26 | public OneJObject asObject() { return new OneJObject((JObject) this.value); } 27 | public OneJValue[] getArrayItems() { return this.value.Children().Select(x => new OneJValue(x)).ToArray(); } 28 | } -------------------------------------------------------------------------------- /packages/implementations/OneLang-Json-v0.1/Java/JsToJava.yaml: -------------------------------------------------------------------------------- 1 | expressions: 2 | JSON.stringify(obj): 3 | #includes: [com.google.gson.*] 4 | #template: new GsonBuilder().disableHtmlEscaping().create().toJson($obj) 5 | includes: [io.onelang.std.json.JSON] 6 | template: JSON.stringify($obj) -------------------------------------------------------------------------------- /packages/implementations/OneLang-Json-v0.1/Java/src/JSON.java: -------------------------------------------------------------------------------- 1 | package io.onelang.std.json; 2 | 3 | import com.google.gson.*; 4 | 5 | public class JSON { 6 | public static String stringify(Object obj) { 7 | Gson gson = new GsonBuilder().disableHtmlEscaping().create(); 8 | String json = gson.toJson(obj); 9 | return json; 10 | } 11 | } -------------------------------------------------------------------------------- /packages/implementations/OneLang-Json-v0.1/Java/src/OneJObject.java: -------------------------------------------------------------------------------- 1 | package io.onelang.std.json; 2 | 3 | import com.google.gson.*; 4 | 5 | public class OneJObject { 6 | JsonObject value; 7 | 8 | public OneJObject(JsonObject value) { 9 | this.value = value; 10 | } 11 | 12 | public OneJValue get(String name) { 13 | return new OneJValue(this.value.get(name)); 14 | } 15 | } -------------------------------------------------------------------------------- /packages/implementations/OneLang-Json-v0.1/Java/src/OneJValue.java: -------------------------------------------------------------------------------- 1 | package io.onelang.std.json; 2 | 3 | import com.google.gson.*; 4 | 5 | public class OneJValue { 6 | public JsonElement value; 7 | 8 | public OneJValue(JsonElement value) { 9 | this.value = value; 10 | } 11 | 12 | public String asString() { return this.value.getAsString(); } 13 | public long asNumber() { return this.value.getAsLong(); } 14 | public Boolean asBool() { return this.value.getAsBoolean(); } 15 | public OneJObject asObject() { return new OneJObject(this.value.getAsJsonObject()); } 16 | 17 | public OneJValue[] getArrayItems() { 18 | JsonArray arr = this.value.getAsJsonArray(); 19 | OneJValue[] result = new OneJValue[arr.size()]; 20 | for (int i = 0; i < arr.size(); i++) 21 | result[i] = new OneJValue(arr.get(i)); 22 | return result; 23 | } 24 | } -------------------------------------------------------------------------------- /packages/implementations/OneLang-Json-v0.1/Java/src/OneJson.java: -------------------------------------------------------------------------------- 1 | package io.onelang.std.json; 2 | 3 | import com.google.gson.*; 4 | 5 | public class OneJson { 6 | public static OneJValue parse(String content) { 7 | JsonParser parser = new JsonParser(); 8 | JsonElement value = parser.parse(content); 9 | return new OneJValue(value); 10 | } 11 | } -------------------------------------------------------------------------------- /packages/implementations/OneLang-Json-v0.1/PHP/JsToPhp.yaml: -------------------------------------------------------------------------------- 1 | expressions: 2 | JSON.stringify(obj): json_encode($obj, JSON_UNESCAPED_SLASHES) 3 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-Json-v0.1/PHP/src/OneJson.php: -------------------------------------------------------------------------------- 1 | value = $value; } 7 | 8 | function asObject() { return new OneJObject($this->value); } 9 | function asString() { return $this->value; } 10 | function getArrayItems() { return array_map(function($item) { return new OneJValue($item); }, $this->value); } 11 | } 12 | 13 | class OneJObject { 14 | function __construct($value) { $this->value = $value; } 15 | 16 | function get($key) { return new OneJValue($this->value[$key]); } 17 | } 18 | 19 | class OneJson { 20 | static function parse($str) { 21 | return new OneJValue(json_decode($str, TRUE)); 22 | } 23 | } -------------------------------------------------------------------------------- /packages/implementations/OneLang-Json-v0.1/Python/JsToPython.yaml: -------------------------------------------------------------------------------- 1 | expressions: 2 | JSON.stringify(obj): 3 | includes: [json] 4 | template: json.dumps($obj, separators=(',', ':')) -------------------------------------------------------------------------------- /packages/implementations/OneLang-Json-v0.1/Python/src/OneJson.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | class OneJValue: 4 | def __init__(self, value): 5 | self.value = value 6 | 7 | def as_object(self): 8 | return OneJObject(self.value) 9 | 10 | def as_string(self): 11 | return self.value 12 | 13 | def get_array_items(self): 14 | return [OneJValue(item) for item in self.value] 15 | 16 | class OneJObject: 17 | def __init__(self, value): 18 | self.value = value 19 | 20 | def get(self, key): 21 | return OneJValue(self.value[key]) 22 | 23 | class OneJson: 24 | @staticmethod 25 | def parse(content): 26 | return OneJValue(json.loads(content)) -------------------------------------------------------------------------------- /packages/implementations/OneLang-Json-v0.1/Python/src/__init__.py: -------------------------------------------------------------------------------- 1 | from .OneJson import * 2 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-Json-v0.1/langs/csharp.yaml: -------------------------------------------------------------------------------- 1 | implements: 2 | - interface: { name: One.Json, minver: 0.1, maxver: 0.1 } 3 | language: csharp 4 | nativePackages: 5 | - name: Newtonsoft.Json 6 | version: 12.0.3 7 | implementation: 8 | classes: 9 | OneJson: 10 | includes: [Newtonsoft.Json.Linq] 11 | methods: 12 | parse: "JToken.Parse({{str}})" 13 | OneJValue: 14 | methods: 15 | isObject: "({{self}}.Type == JTokenType.Object)" 16 | isArray: "({{self}}.Type == JTokenType.Array)" 17 | isString: "({{self}}.Type == JTokenType.String)" 18 | isNumber: "({{self}}.Type == JTokenType.Integer)" 19 | isBool: "({{self}}.Type == JTokenType.Boolean)" 20 | isNull: "({{self}}.Type == JTokenType.Null)" 21 | asString: "(string)((JValue){{self}}).Value" 22 | asNumber: "(long)((JValue){{self}}).Value" 23 | asBool: "(bool)((JValue){{self}}).Value" 24 | asObject: "{{self}}" 25 | getArrayItems: "{{self}}" 26 | OneJObject: 27 | methods: 28 | getProperties: 29 | includes: [System.Linq] 30 | template: "{{self}}.Cast().ToList()" 31 | get: "{{self}}[{{name}}]" 32 | OneJProperty: 33 | methods: 34 | getName: "{{self}}.Name" 35 | getValue: "{{self}}.Value" 36 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-Json-v0.1/langs/java.yaml: -------------------------------------------------------------------------------- 1 | implements: 2 | - interface: { name: One.Json, minver: 0.1, maxver: 0.1 } 3 | language: java 4 | implementation: 5 | classes: 6 | OneJson: 7 | methods: 8 | parse: 9 | includes: [com.google.gson.*] 10 | template: "new JsonParser().parse({{str}})" 11 | OneJValue: 12 | type: JsonElement 13 | includes: [com.google.gson.*] 14 | methods: 15 | isObject: "{{self}}.isJsonObject()" 16 | isArray: "{{self}}.isJsonArray()" 17 | isString: "({{self}}.isJsonPrimitive() && ((JsonPrimitive){{self}}).isString())" 18 | isNumber: "({{self}}.isJsonPrimitive() && ((JsonPrimitive){{self}}).isNumber())" 19 | isBool: "({{self}}.isJsonPrimitive() && ((JsonPrimitive){{self}}).isBoolean())" 20 | isNull: "{{self}}.isJsonNull()" 21 | asString: "{{self}}.getAsString()" 22 | asNumber: "{{self}}.getAsInt()" 23 | asBool: "{{self}}.getAsBoolean()" 24 | asObject: "{{self}}.getAsJsonObject()" 25 | getArrayItems: "{{self}}.getAsJsonArray()" 26 | OneJObject: 27 | type: JsonObject 28 | includes: [com.google.gson.*] 29 | methods: 30 | getProperties: "new ArrayList({{self}}.entrySet())" 31 | get: "{{self}}.get({{name}})" 32 | OneJProperty: 33 | type: Map.Entry 34 | includes: [java.util.Map] 35 | methods: 36 | getName: "{{self}}.getKey()" 37 | getValue: "{{self}}.getValue()" 38 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-Json-v0.1/langs/javascript.yaml: -------------------------------------------------------------------------------- 1 | implements: 2 | - interface: { name: One.Json, minver: 0.1, maxver: 0.1 } 3 | language: javascript 4 | implementation: 5 | classes: 6 | OneJson: 7 | methods: 8 | parse: "JSON.parse({{str}})" 9 | OneJValue: 10 | methods: 11 | isObject: "(typeof ({{self}}) === 'object' && !Array.isArray({{self}}))" 12 | isArray: "Array.isArray({{self}})" 13 | isString: "(typeof ({{self}}) === 'string')" 14 | isNumber: "(typeof ({{self}}) === 'number')" 15 | isBool: "(typeof ({{self}}) === 'boolean')" 16 | isNull: "({{self}} === null)" 17 | asString: "{{self}}" 18 | asNumber: "{{self}}" 19 | asBool: "{{self}}" 20 | asObject: "{{self}}" 21 | getArrayItems: "{{self}}" 22 | OneJObject: 23 | methods: 24 | getProperties: "Object.keys({{self}})" 25 | get: "{{self}}[{{name}}]" 26 | OneJProperty: 27 | methods: 28 | getName: "{{self}}" 29 | getValue: "{{obj}}[{{self}}]" 30 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-Json-v0.1/langs/php.yaml: -------------------------------------------------------------------------------- 1 | implements: 2 | - interface: { name: One.Json, minver: 0.1, maxver: 0.1 } 3 | language: php 4 | implementation: 5 | classes: 6 | OneJson: 7 | methods: 8 | parse: "json_decode({{str}})" 9 | OneJValue: 10 | methods: 11 | isObject: "is_object({{self}})" 12 | isArray: "is_array({{self}})" 13 | isString: "is_string({{self}})" 14 | isNumber: "is_numeric({{self}})" 15 | isBool: "is_bool({{self}})" 16 | isNull: "is_null({{self}})" 17 | asString: "{{self}}" 18 | asNumber: "{{self}}" 19 | asBool: "{{self}}" 20 | asObject: "{{self}}" 21 | getArrayItems: "{{self}}" 22 | OneJObject: 23 | methods: 24 | getProperties: "array_keys((array){{self}})" 25 | get: "{{self}}->{{{name}}}" 26 | OneJProperty: 27 | methods: 28 | getName: "{{self}}" 29 | getValue: "{{obj}}->{{{self}}}" 30 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-Json-v0.1/langs/python.yaml: -------------------------------------------------------------------------------- 1 | implements: 2 | - interface: { name: One.Json, minver: 0.1, maxver: 0.1 } 3 | language: python 4 | implementation: 5 | classes: 6 | OneJson: 7 | methods: 8 | parse: 9 | includes: [json] 10 | template: "json.loads({{str}})" 11 | OneJValue: 12 | methods: 13 | isObject: "isinstance({{self}}, dict)" 14 | isArray: "isinstance({{self}}, list)" 15 | isString: "isinstance({{self}}, str)" 16 | isNumber: "isinstance({{self}}, (int, long, float))" 17 | isBool: "({{self}} == True or {{self}} == False)" 18 | isNull: "({{self}} is None)" 19 | asString: "{{self}}" 20 | asNumber: "{{self}}" 21 | asBool: "{{self}}" 22 | asObject: "{{self}}" 23 | getArrayItems: "{{self}}" 24 | OneJObject: 25 | methods: 26 | getProperties: "{{self}}.keys()" 27 | get: "{{self}}[{{name}}]" 28 | OneJProperty: 29 | methods: 30 | getName: "{{self}}" 31 | getValue: "{{obj}}[{{self}}]" 32 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-Json-v0.1/langs/ruby.yaml: -------------------------------------------------------------------------------- 1 | implements: 2 | - interface: { name: One.Json, minver: 0.1, maxver: 0.1 } 3 | language: ruby 4 | implementation: 5 | classes: 6 | OneJson: 7 | methods: 8 | parse: 9 | includes: [json] 10 | template: "JSON.parse({{str}})" 11 | OneJValue: 12 | methods: 13 | isObject: "{{self}}.is_a?(Hash)" 14 | isArray: "{{self}}.is_a?(Array)" 15 | isString: "{{self}}.is_a?(String)" 16 | isNumber: "{{self}}.is_a?(Numeric)" 17 | isBool: "({{self}} == true or {{self}} == false)" 18 | isNull: "({{self}} == nil)" 19 | asString: "{{self}}" 20 | asNumber: "{{self}}" 21 | asBool: "{{self}}" 22 | asObject: "{{self}}" 23 | getArrayItems: "{{self}}" 24 | OneJObject: 25 | methods: 26 | getProperties: "{{self}}.keys" 27 | get: "{{self}}[{{name}}]" 28 | OneJProperty: 29 | methods: 30 | getName: "{{self}}" 31 | getValue: "{{obj}}[{{self}}]" 32 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-Json-v0.1/langs/swift.yaml: -------------------------------------------------------------------------------- 1 | implements: 2 | - interface: { name: One.Json, minver: 0.1, maxver: 0.1 } 3 | language: swift 4 | implementation: 5 | classes: 6 | OneJson: 7 | includes: [Foundation] 8 | methods: 9 | parse: "try? JSONSerialization.jsonObject(with: {{str}}.data(using: .utf8)!)" 10 | OneJValue: 11 | type: Any 12 | methods: 13 | isObject: "({{self}} is [String: Any?])" 14 | isArray: "({{self}} is [Any])" 15 | isString: "({{self}} is String)" 16 | isNumber: "({{self}} is Int)" 17 | isBool: "({{self}} is Bool)" 18 | isNull: "({{self}} == nil)" 19 | asString: "({{self}} as! String)" 20 | asNumber: "({{self}} as! Int)" 21 | asBool: "({{self}} as! Bool)" 22 | asObject: "({{self}} as? [String: Any?])" 23 | getArrayItems: "{{self}}" 24 | OneJObject: 25 | type: Any 26 | methods: 27 | getProperties: "Array({{self}}!.keys)" 28 | get: "{{self}}![{{name}}]" 29 | OneJProperty: 30 | type: String 31 | methods: 32 | getName: "{{self}}" 33 | getValue: "({{obj}} as! [String: Any?])[{{self}}!]!" -------------------------------------------------------------------------------- /packages/implementations/OneLang-Json-v0.1/langs/typescript.yaml: -------------------------------------------------------------------------------- 1 | implements: 2 | - interface: { name: One.Json, minver: 0.1, maxver: 0.1 } 3 | language: typescript 4 | implementation: 5 | classes: 6 | OneJson: 7 | methods: 8 | parse: "JSON.parse({{str}})" 9 | OneJValue: 10 | methods: 11 | isObject: "(typeof ({{self}}) === 'object' && !Array.isArray({{self}}))" 12 | isArray: "Array.isArray({{self}})" 13 | isString: "(typeof ({{self}}) === 'string')" 14 | isNumber: "(typeof ({{self}}) === 'number')" 15 | isBool: "(typeof ({{self}}) === 'boolean')" 16 | isNull: "({{self}} === null)" 17 | asString: "{{self}}" 18 | asNumber: "{{self}}" 19 | asBool: "{{self}}" 20 | asObject: "{{self}}" 21 | getArrayItems: "{{self}}" 22 | OneJObject: 23 | methods: 24 | getProperties: "Object.keys({{self}})" 25 | get: "{{self}}[{{name}}]" 26 | OneJProperty: 27 | methods: 28 | getName: "{{self}}" 29 | getValue: "{{obj}}[{{self}}]" 30 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-Json-v0.1/package.yaml: -------------------------------------------------------------------------------- 1 | file-version: 1 2 | vendor: OneLang 3 | name: Json 4 | version: 0.1 5 | includes: 6 | - langs/csharp.yaml 7 | - langs/go.yaml 8 | - langs/java.yaml 9 | - langs/javascript.yaml 10 | - langs/php.yaml 11 | - langs/python.yaml 12 | - langs/ruby.yaml 13 | - langs/swift.yaml 14 | - langs/typescript.yaml 15 | languages: 16 | java: 17 | package-dir: json 18 | native-src-dir: Java/src 19 | native-dependencies: 20 | - { name: com.google.code.gson:gson, version: 2.8.6 } 21 | generator-plugins: [Java/JsToJava.yaml] 22 | csharp: 23 | native-src-dir: CSharp/src 24 | native-dependencies: 25 | - { name: Newtonsoft.Json, version: 12.0.3 } 26 | php: 27 | native-src-dir: PHP/src 28 | generator-plugins: [PHP/JsToPhp.yaml] 29 | python: 30 | package-dir: onelang_json 31 | native-src-dir: Python/src 32 | generator-plugins: [Python/JsToPython.yaml] 33 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-Reflect-v0.1/CSharp/src/ReflectedValue.cs: -------------------------------------------------------------------------------- 1 | using One.Ast; 2 | 3 | public class ReflectedValue 4 | { 5 | public IType getDeclaredType() { return null; } 6 | public string getStringValue() { return null; } 7 | public bool getBooleanValue() { return false; } 8 | public ReflectedValue[] getArrayItems() { return null; } 9 | public string[] getMapKeys() { return null; } 10 | public object getUniqueIdentifier() { return null; } 11 | public IType getValueType() { return null; } 12 | public ReflectedValue getField(string name) { return null; } 13 | public string getEnumValueAsString() { return null; } 14 | public bool isNull() { return false; } 15 | public ReflectedValue getMapValue(string key) { return null; } 16 | } -------------------------------------------------------------------------------- /packages/implementations/OneLang-Reflect-v0.1/Java/src/ReflectedValue.java: -------------------------------------------------------------------------------- 1 | package io.onelang.std.reflect; 2 | 3 | import OneLang.One.Ast.Interfaces.IType; 4 | 5 | public class ReflectedValue 6 | { 7 | public IType getDeclaredType() { return null; } 8 | public String getStringValue() { return null; } 9 | public Boolean getBooleanValue() { return false; } 10 | public ReflectedValue[] getArrayItems() { return null; } 11 | public String[] getMapKeys() { return null; } 12 | public Object getUniqueIdentifier() { return null; } 13 | public IType getValueType() { return null; } 14 | public ReflectedValue getField(String name) { return null; } 15 | public String getEnumValueAsString() { return null; } 16 | public Boolean isNull() { return false; } 17 | public ReflectedValue getMapValue(String key) { return null; } 18 | } -------------------------------------------------------------------------------- /packages/implementations/OneLang-Reflect-v0.1/langs/csharp.yaml: -------------------------------------------------------------------------------- 1 | implements: 2 | - interface: { name: One.Reflect, minver: 0.1, maxver: 0.1 } 3 | language: csharp 4 | implementation: 5 | classes: 6 | OneMethod: 7 | methods: 8 | call: "{{self}}.Call({{obj}}, ({{args}}).ToArray())" 9 | templates: 10 | beforeFields: 11 | args: [class] 12 | template: |- 13 | {{if class.attributes["reflect"]}} 14 | static {{class.name}}() 15 | { 16 | OneReflect.Publish(typeof({{class.name}})); 17 | } 18 | {{/if}} 19 | native-includes: [one.cs] -------------------------------------------------------------------------------- /packages/implementations/OneLang-Reflect-v0.1/langs/go.yaml: -------------------------------------------------------------------------------- 1 | implements: 2 | - interface: { name: One.Reflect, minver: 0.1, maxver: 0.1 } 3 | language: go 4 | implementation: 5 | classes: 6 | OneReflect: 7 | includes: [one] 8 | template: "one.Reflect" 9 | templates: 10 | afterClasses: 11 | args: [] 12 | template: |- 13 | {{if reflectedClasses.length > 0}} 14 | func init() { 15 | {{for class in reflectedClasses|sep=\n\n}} 16 | one.Reflect_SetupClass((*{{class.name}})(nil), 17 | []*one.Field{ 18 | {{for field in class.fields}} 19 | {{if field.static}} 20 | one.Reflect_StaticField("{{field.name}}", &{{class.name}}{{field.name}}), 21 | {{else}} 22 | one.Reflect_InstanceField("{{field.name}}"), 23 | {{/if}} 24 | {{/for}} 25 | }, 26 | []*one.Method{ 27 | {{for method in class.methods}} 28 | {{if method.static}} 29 | one.Reflect_StaticMethod("{{method.name}}", {{class.name}}_{{method.name}}), 30 | {{else}} 31 | one.Reflect_InstanceMethod("{{method.name}}"), 32 | {{/if}} 33 | {{/for}} 34 | }); 35 | {{/for}} 36 | } 37 | {{/if}} 38 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-Reflect-v0.1/langs/java.yaml: -------------------------------------------------------------------------------- 1 | implements: 2 | - interface: { name: One.Reflect, minver: 0.1, maxver: 0.1 } 3 | language: java 4 | implementation: 5 | templates: 6 | beginClass: 7 | args: [class] 8 | template: |- 9 | {{if class.attributes["reflect"]}} 10 | static { 11 | OneReflect.publish({{class.name}}.class); 12 | } 13 | {{/if}} 14 | native-include-dir: java 15 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-Reflect-v0.1/langs/javascript.yaml: -------------------------------------------------------------------------------- 1 | implements: 2 | - interface: { name: One.Reflect, minver: 0.1, maxver: 0.1 } 3 | language: javascript 4 | native-includes: ["OneReflect.js"] 5 | implementation: 6 | includeSources: 7 | OneReflect: "OneLang-Reflect-v0.1/OneReflect" 8 | classes: 9 | OneReflect: 10 | includes: ["OneReflect"] 11 | template: "OneReflect" 12 | templates: 13 | endClass: 14 | args: [class] 15 | template: |- 16 | {{if class.attributes["reflect"]}} 17 | OneReflect.setupClass(new OneReflect.Class({{class.name}}, [ 18 | {{for field in class.fields|sep=\n}} 19 | new OneReflect.Field("{{field.name}}", {{field.static}}, "{{field.type}}"), 20 | {{/for}} 21 | ], [ 22 | {{for method in class.methods|sep=\n}} 23 | new OneReflect.Method("{{method.name}}", {{method.static}}, "{{method.returnType}}", [ 24 | {{for param in method.parameters|sep=\n}} 25 | new OneReflect.MethodArgument("{{param.name}}", "{{param.type}}"), 26 | {{/for}} 27 | ]), 28 | {{/for}} 29 | ])); 30 | {{/if}} 31 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-Reflect-v0.1/langs/perl.yaml: -------------------------------------------------------------------------------- 1 | implements: 2 | - interface: { name: One.Reflect, minver: 0.1, maxver: 0.1 } 3 | language: perl 4 | implementation: 5 | classes: 6 | OneReflect: 7 | includes: [one] 8 | template: "OneReflect" 9 | templates: 10 | endClass: 11 | args: [class] 12 | template: |- 13 | {{if class.attributes["reflect"]}} 14 | OneReflect::setup_class(new OneClass("{{class.name}}", [ 15 | {{for field in class.fields|sep=\n}} 16 | new OneField("{{field.name}}", {{if field.static}}1{{else}}0{{/if}}, "{{field.type}}"), 17 | {{/for}} 18 | ], [ 19 | {{for method in class.methods|sep=\n}} 20 | new OneMethod("{{method.name}}", {{if method.static}}1{{else}}0{{/if}}, "{{method.returnType}}", [ 21 | {{for param in method.parameters|sep=\n}} 22 | new OneMethodArgument("{{param.name}}", "{{param.type}}"), 23 | {{/for}} 24 | ]), 25 | {{/for}} 26 | ])); 27 | {{/if}} 28 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-Reflect-v0.1/langs/php.yaml: -------------------------------------------------------------------------------- 1 | implements: 2 | - interface: { name: One.Reflect, minver: 0.1, maxver: 0.1 } 3 | language: php 4 | implementation: 5 | classes: 6 | OneReflect: 7 | includes: [one] 8 | templates: 9 | endClass: 10 | args: [class] 11 | template: |- 12 | {{if class.attributes["reflect"]}} 13 | OneReflect::setupClass(new OneClass("{{class.name}}", [ 14 | {{for field in class.fields|sep=\n}} 15 | new OneField("{{field.name}}", {{if field.static}}true{{else}}false{{/if}}, "{{field.type}}"), 16 | {{/for}} 17 | ], [ 18 | {{for method in class.methods|sep=\n}} 19 | new OneMethod("{{method.name}}", {{if method.static}}true{{else}}false{{/if}}, "{{method.returnType}}", [ 20 | {{for param in method.parameters|sep=\n}} 21 | new OneMethodArgument("{{param.name}}", "{{param.type}}"), 22 | {{/for}} 23 | ]), 24 | {{/for}} 25 | ])); 26 | {{/if}} 27 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-Reflect-v0.1/langs/python.yaml: -------------------------------------------------------------------------------- 1 | implements: 2 | - interface: { name: One.Reflect, minver: 0.1, maxver: 0.1 } 3 | language: python 4 | native-includes: ["OneReflect.py"] 5 | implementation: 6 | classes: 7 | OneReflect: 8 | includes: ["OneReflect"] 9 | template: "OneReflect" 10 | templates: 11 | endClass: 12 | args: [class] 13 | template: |- 14 | {{if class.attributes["reflect"]}} 15 | OneReflect.setup_class(OneReflect.Class({{class.name}}, [ 16 | {{for field in class.fields|sep=\n}} 17 | OneReflect.Field("{{field.name}}", {{if field.static}}True{{else}}False{{/if}}, "{{field.type}}"), 18 | {{/for}} 19 | ], [ 20 | {{for method in class.methods|sep=\n}} 21 | OneReflect.Method("{{method.name}}", {{if method.static}}True{{else}}False{{/if}}, "{{method.returnType}}", [ 22 | {{for param in method.parameters|sep=\n}} 23 | OneReflect.MethodArgument("{{param.name}}", "{{param.type}}"), 24 | {{/for}} 25 | ]), 26 | {{/for}} 27 | ])); 28 | {{/if}} 29 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-Reflect-v0.1/langs/ruby.yaml: -------------------------------------------------------------------------------- 1 | implements: 2 | - interface: { name: One.Reflect, minver: 0.1, maxver: 0.1 } 3 | language: ruby 4 | native-includes: ["OneReflect.rb"] 5 | implementation: 6 | classes: 7 | OneReflect: 8 | includes: ["OneReflect"] 9 | template: "OneReflect" 10 | templates: 11 | endClass: 12 | args: [class] 13 | template: |- 14 | {{if class.attributes["reflect"]}} 15 | OneReflect::setup_class(OneReflect::Class.new({{class.name}}, [ 16 | {{for field in class.fields|sep=\n}} 17 | OneReflect::Field.new("{{field.name}}", {{field.static}}, "{{field.type}}"), 18 | {{/for}} 19 | ], [ 20 | {{for method in class.methods|sep=\n}} 21 | OneReflect::Method.new("{{method.name}}", {{method.static}}, "{{method.returnType}}", [ 22 | {{for param in method.parameters|sep=\n}} 23 | OneReflect::MethodArgument.new("{{param.name}}", "{{param.type}}"), 24 | {{/for}} 25 | ]), 26 | {{/for}} 27 | ])); 28 | {{/if}} 29 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-Reflect-v0.1/langs/swift.yaml: -------------------------------------------------------------------------------- 1 | implements: 2 | - interface: { name: One.Reflect, minver: 0.1, maxver: 0.1 } 3 | language: swift 4 | implementation: 5 | templates: 6 | endClass: 7 | args: [class] 8 | template: |- 9 | {{if class.attributes["reflect"]}} 10 | let _ = OneReflect.addClass(OneClass(name: "{{class.name}}")) 11 | {{for field in class.fields}} 12 | {{if field.static}} 13 | .addField(OneField("{{field.name}}", true, "{{field.type}}", { _ in {{class.name}}.{{field.name}} }, { {{class.name}}.{{field.name}} = $1 as! {{field.type}} })) 14 | {{else}} 15 | .addField(OneField("{{field.name}}", false, "{{field.type}}", { ($0 as! {{class.name}}).{{field.name}} }, { ($0 as! {{class.name}}).{{field.name}} = $1 as! {{field.type}} })) 16 | {{/if}} 17 | {{/for}} 18 | {{for method in class.methods}} 19 | .addMethod(OneMethod("{{method.name}}", {{if method.static}}true{{else}}false{{/if}}, "{{method.returnType}}", [ 20 | {{for param in method.parameters}} 21 | OneMethodArgument("{{param.name}}", "{{param.type}}"), 22 | {{/for}} 23 | ], 24 | { obj, args in 25 | {{if method.static|inline}} 26 | {{class.name}} 27 | {{else|inline}} 28 | (obj as! {{class.name}}) 29 | {{/if}} 30 | .{{method.name}}( 31 | {{for param in method.parameters|inline sep=,}} 32 | {{param.name}}: args[{{param_idx}}] as! {{param.type}} 33 | {{/for}} 34 | ) })) 35 | {{/for}} 36 | {{/if}} 37 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-Reflect-v0.1/langs/typescript.yaml: -------------------------------------------------------------------------------- 1 | implements: 2 | - interface: { name: One.Reflect, minver: 0.1, maxver: 0.1 } 3 | language: typescript 4 | implementation: 5 | classes: 6 | OneReflect: 7 | includes: ["one"] 8 | template: "one.Reflect" 9 | templates: 10 | endClass: 11 | args: [class] 12 | template: |- 13 | {{if class.attributes["reflect"]}} 14 | one.Reflect.setupClass(new one.Class({{class.name}}, [ 15 | {{for field in class.fields|sep=\n}} 16 | new one.Field("{{field.name}}", {{field.static}}, "{{field.type}}"), 17 | {{/for}} 18 | ], [ 19 | {{for method in class.methods|sep=\n}} 20 | new one.Method("{{method.name}}", {{method.static}}, "{{method.returnType}}", [ 21 | {{for param in method.parameters|sep=\n}} 22 | new one.MethodArgument("{{param.name}}", "{{param.type}}"), 23 | {{/for}} 24 | ]), 25 | {{/for}} 26 | ])); 27 | {{/if}} 28 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-Reflect-v0.1/native/java/OneClass.java: -------------------------------------------------------------------------------- 1 | import java.util.List; 2 | import java.util.ArrayList; 3 | import java.util.Map; 4 | import java.util.TreeMap; 5 | import java.lang.reflect.*; 6 | 7 | public class OneClass 8 | { 9 | public Class clazz; 10 | public String name; 11 | 12 | public static Map fields = new TreeMap(String.CASE_INSENSITIVE_ORDER); 13 | public static Map methods = new TreeMap(String.CASE_INSENSITIVE_ORDER); 14 | 15 | public OneClass(Class clazz) 16 | { 17 | this.clazz = clazz; 18 | this.name = clazz.getName(); 19 | 20 | for (Field field : clazz.getDeclaredFields()) { 21 | OneField oneField = new OneField(field); 22 | this.fields.put(oneField.name, oneField); 23 | } 24 | 25 | for (Method method : clazz.getDeclaredMethods()) { 26 | OneMethod oneMethod = new OneMethod(method); 27 | this.methods.put(oneMethod.name, oneMethod); 28 | } 29 | } 30 | 31 | public OneField getField(String name) { 32 | return fields.get(name); 33 | } 34 | 35 | public OneMethod getMethod(String name) { 36 | return methods.get(name); 37 | } 38 | 39 | public List getFields() { 40 | return new ArrayList(fields.values()); 41 | } 42 | 43 | public List getMethods() { 44 | return new ArrayList(methods.values()); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-Reflect-v0.1/native/java/OneField.java: -------------------------------------------------------------------------------- 1 | import java.util.List; 2 | import java.util.ArrayList; 3 | import java.util.Map; 4 | import java.util.TreeMap; 5 | import java.lang.reflect.*; 6 | 7 | public class OneField 8 | { 9 | public Field field; 10 | 11 | public String name; 12 | public boolean isStatic; 13 | 14 | public OneField(Field field) 15 | { 16 | this.field = field; 17 | this.name = field.getName(); 18 | this.isStatic = Modifier.isStatic(field.getModifiers()); 19 | } 20 | 21 | public Object getValue(Object obj) throws Exception { 22 | return field.get(obj); 23 | } 24 | 25 | public void setValue(Object obj, Object value) throws Exception { 26 | field.set(obj, value); 27 | } 28 | } -------------------------------------------------------------------------------- /packages/implementations/OneLang-Reflect-v0.1/native/java/OneMethod.java: -------------------------------------------------------------------------------- 1 | import java.util.List; 2 | import java.util.ArrayList; 3 | import java.util.Map; 4 | import java.util.TreeMap; 5 | import java.lang.reflect.*; 6 | 7 | public class OneMethod 8 | { 9 | public Method method; 10 | 11 | public String name; 12 | public boolean isStatic; 13 | 14 | public OneMethod(Method method) 15 | { 16 | this.method = method; 17 | this.name = method.getName(); 18 | this.isStatic = Modifier.isStatic(method.getModifiers()); 19 | } 20 | 21 | public Object call(Object obj, List args) throws Exception { 22 | return method.invoke(obj, args.toArray(new Object[args.size()])); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-Reflect-v0.1/native/java/OneReflect.java: -------------------------------------------------------------------------------- 1 | import java.util.List; 2 | import java.util.ArrayList; 3 | import java.util.Map; 4 | import java.util.TreeMap; 5 | import java.lang.reflect.*; 6 | 7 | public class OneReflect 8 | { 9 | public static Map publishedTypes = new TreeMap(String.CASE_INSENSITIVE_ORDER); 10 | 11 | public static OneClass getClass(Object obj) { 12 | return getClassByName(obj.getClass().getName()); 13 | } 14 | 15 | public static OneClass getClassByName(String name) { 16 | return publishedTypes.get(name); 17 | } 18 | 19 | public static void publish(Class clazz) { 20 | publishedTypes.put(clazz.getName(), new OneClass(clazz)); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-Reflect-v0.1/package.yaml: -------------------------------------------------------------------------------- 1 | file-version: 1 2 | vendor: OneLang 3 | name: Reflect 4 | version: 0.1 5 | includes: 6 | - langs/cpp.yaml 7 | - langs/csharp.yaml 8 | - langs/go.yaml 9 | - langs/java.yaml 10 | - langs/javascript.yaml 11 | - langs/perl.yaml 12 | - langs/php.yaml 13 | - langs/python.yaml 14 | - langs/ruby.yaml 15 | - langs/swift.yaml 16 | - langs/typescript.yaml 17 | languages: 18 | csharp: 19 | native-src-dir: CSharp/src 20 | java: 21 | package-dir: reflect 22 | native-src-dir: Java/src 23 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-Regex-v0.1/langs/cpp.yaml: -------------------------------------------------------------------------------- 1 | implements: 2 | - interface: { name: One.Regex, minver: 0.1, maxver: 0.1 } 3 | language: cpp 4 | native-include-dir: "cpp" 5 | implementation: 6 | classes: 7 | OneRegex: 8 | includes: ["OneLang-Regex-v0.1/OneRegex.hpp"] -------------------------------------------------------------------------------- /packages/implementations/OneLang-Regex-v0.1/langs/csharp.yaml: -------------------------------------------------------------------------------- 1 | implements: 2 | - interface: { name: One.Regex, minver: 0.1, maxver: 0.1 } 3 | language: csharp 4 | native-includes: [one.cs] -------------------------------------------------------------------------------- /packages/implementations/OneLang-Regex-v0.1/langs/go.yaml: -------------------------------------------------------------------------------- 1 | implements: 2 | - interface: { name: One.Regex, minver: 0.1, maxver: 0.1 } 3 | language: go 4 | implementation: 5 | classes: 6 | OneRegex: 7 | includes: [one] 8 | template: "one.Regex" 9 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-Regex-v0.1/langs/java.yaml: -------------------------------------------------------------------------------- 1 | implements: 2 | - interface: { name: One.Regex, minver: 0.1, maxver: 0.1 } 3 | language: java 4 | native-include-dir: java 5 | implementation: 6 | classes: 7 | OneRegex: 8 | includes: ["io.onelang.OneRegex"] -------------------------------------------------------------------------------- /packages/implementations/OneLang-Regex-v0.1/langs/javascript.yaml: -------------------------------------------------------------------------------- 1 | implements: 2 | - interface: { name: One.Regex, minver: 0.1, maxver: 0.1 } 3 | language: javascript 4 | native-includes: ["OneRegex.js"] 5 | implementation: 6 | includeSources: 7 | OneRegex: "OneLang-Regex-v0.1/OneRegex" 8 | classes: 9 | OneRegex: 10 | includes: ["OneRegex"] 11 | template: "OneRegex" 12 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-Regex-v0.1/langs/perl.yaml: -------------------------------------------------------------------------------- 1 | implements: 2 | - interface: { name: One.Regex, minver: 0.1, maxver: 0.1 } 3 | language: perl 4 | implementation: 5 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-Regex-v0.1/langs/php.yaml: -------------------------------------------------------------------------------- 1 | implements: 2 | - interface: { name: One.Regex, minver: 0.1, maxver: 0.1 } 3 | language: php 4 | implementation: 5 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-Regex-v0.1/langs/python.yaml: -------------------------------------------------------------------------------- 1 | implements: 2 | - interface: { name: One.Regex, minver: 0.1, maxver: 0.1 } 3 | language: python 4 | native-includes: ["OneRegex.py"] 5 | implementation: 6 | classes: 7 | OneRegex: 8 | includes: ["OneRegex"] 9 | template: "OneRegex" 10 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-Regex-v0.1/langs/ruby.yaml: -------------------------------------------------------------------------------- 1 | implements: 2 | - interface: { name: One.Regex, minver: 0.1, maxver: 0.1 } 3 | language: ruby 4 | native-includes: ["OneRegex.rb"] 5 | implementation: 6 | classes: 7 | OneRegex: 8 | includes: ["OneRegex"] 9 | template: "OneRegex" 10 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-Regex-v0.1/langs/swift.yaml: -------------------------------------------------------------------------------- 1 | implements: 2 | - interface: { name: One.Regex, minver: 0.1, maxver: 0.1 } 3 | language: swift 4 | implementation: 5 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-Regex-v0.1/langs/typescript.yaml: -------------------------------------------------------------------------------- 1 | implements: 2 | - interface: { name: One.Regex, minver: 0.1, maxver: 0.1 } 3 | language: typescript 4 | implementation: 5 | classes: 6 | OneRegex: 7 | includes: ["one"] 8 | template: "one.Regex" 9 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-Regex-v0.1/native/OneRegex.js: -------------------------------------------------------------------------------- 1 | class OneRegex { 2 | static matchFromIndex(pattern, input, offset) { 3 | const regex = new RegExp(pattern, "gy"); 4 | regex.lastIndex = offset; 5 | const matches = regex.exec(input); 6 | return matches === null ? null : Array.from(matches); 7 | } 8 | } 9 | 10 | module.exports = OneRegex; -------------------------------------------------------------------------------- /packages/implementations/OneLang-Regex-v0.1/native/OneRegex.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | def match_from_index(pattern, input, offset): 4 | patternObj = re.compile(pattern) 5 | match = patternObj.match(input, offset) 6 | if not match: 7 | return None 8 | return list(match.group(0)) + list(match.groups()) 9 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-Regex-v0.1/native/OneRegex.rb: -------------------------------------------------------------------------------- 1 | require 'strscan' 2 | 3 | class OneRegex 4 | def self.match_from_index(pattern, input, offset) 5 | scanner = StringScanner.new input 6 | scanner.pos = offset 7 | return nil if not scanner.scan(Regexp.new pattern) 8 | 9 | result = [] 10 | i = 0 11 | while true do 12 | curr = scanner[i] 13 | break if not curr 14 | result << curr 15 | i = i + 1 16 | end 17 | return result 18 | end 19 | end 20 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-Regex-v0.1/native/cpp/OneRegex.cpp: -------------------------------------------------------------------------------- 1 | #include "OneRegex.hpp" 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | one::vec OneRegex::matchFromIndex(const std::string& pattern, const std::string& input, int offset) { 8 | std::smatch matches; 9 | if (!std::regex_search(input.begin() + offset, input.end(), matches, std::regex("^" + pattern))) 10 | return nullptr; 11 | 12 | auto result = std::make_shared>(); 13 | for(auto match : matches) 14 | result->push_back(match.str()); 15 | return result; 16 | } 17 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-Regex-v0.1/native/cpp/OneRegex.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | 6 | class OneRegex { 7 | public: 8 | static one::vec matchFromIndex(const std::string& pattern, const std::string& input, int offset); 9 | }; 10 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-Regex-v0.1/native/java/io/onelang/OneRegex.java: -------------------------------------------------------------------------------- 1 | package io.onelang; 2 | 3 | import java.util.List; 4 | import java.util.ArrayList; 5 | import java.util.regex.Matcher; 6 | import java.util.regex.Pattern; 7 | 8 | public class OneRegex 9 | { 10 | public static List matchFromIndex(String pattern, String input, int offset) { 11 | Pattern patternObj = Pattern.compile("\\G" + pattern); 12 | Matcher matcher = patternObj.matcher(input); 13 | if (!matcher.find(offset)) 14 | return null; 15 | 16 | ArrayList result = new ArrayList(); 17 | result.add(matcher.group()); 18 | for (int i = 0; i < matcher.groupCount(); i++) 19 | result.add(matcher.group(i)); 20 | return result; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-Regex-v0.1/native/one.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text.RegularExpressions; 5 | 6 | public class OneRegex 7 | { 8 | public static string[] MatchFromIndex(string pattern, string input, int offset) 9 | { 10 | var match = new Regex($"\\G{pattern}").Match(input, offset); 11 | if (!match.Success) return null; 12 | var result = match.Groups.Cast().Select(g => g.Value).ToArray(); 13 | return result; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-Regex-v0.1/native/one.go: -------------------------------------------------------------------------------- 1 | package one 2 | 3 | import "strings" 4 | import "regexp" 5 | 6 | func Regex_MatchFromIndex(pattern string, input string, offset int) []string { 7 | reader := strings.NewReader(input) 8 | reader.Seek(int64(offset), 0) 9 | 10 | re := regexp.MustCompile("^" + pattern) 11 | matchIndices := re.FindReaderSubmatchIndex(reader) 12 | 13 | if matchIndices == nil { 14 | return nil 15 | } 16 | 17 | groupCount := len(matchIndices) / 2 18 | result := make([]string, groupCount) 19 | for i := 0; i < groupCount; i++ { 20 | result[i] = input[offset + matchIndices[i * 2 + 0] : offset + matchIndices[i * 2 + 1]] 21 | } 22 | 23 | return result 24 | } 25 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-Regex-v0.1/native/one.php: -------------------------------------------------------------------------------- 1 | [String]? { 5 | let regex = try! NSRegularExpression(pattern: "^" + pattern) 6 | guard let match = regex.firstMatch(in: input, range: NSMakeRange(offset, input.utf16.count - offset)) else { return nil } 7 | 8 | var results = [String]() 9 | for i in 0 ... match.numberOfRanges - 1 { 10 | let range = match.range(at: i) 11 | let groupValue = input.substring(with: Range(range, in: input)!) 12 | results.append(groupValue) 13 | } 14 | return results 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-Regex-v0.1/native/one.ts: -------------------------------------------------------------------------------- 1 | export class Regex { 2 | static matchFromIndex(pattern: string, input: string, offset: number) { 3 | const regex = new RegExp(pattern, "gy"); 4 | regex.lastIndex = offset; 5 | const matches = regex.exec(input); 6 | return matches === null ? null : Array.from(matches); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-Regex-v0.1/package.yaml: -------------------------------------------------------------------------------- 1 | file-version: 1 2 | vendor: OneLang 3 | name: Regex 4 | version: 0.1 5 | includes: 6 | - langs/cpp.yaml 7 | - langs/csharp.yaml 8 | - langs/go.yaml 9 | - langs/java.yaml 10 | - langs/javascript.yaml 11 | - langs/perl.yaml 12 | - langs/php.yaml 13 | - langs/python.yaml 14 | - langs/ruby.yaml 15 | - langs/swift.yaml 16 | - langs/typescript.yaml 17 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-Yaml-v0.1/CSharp/src/OneYaml.cs: -------------------------------------------------------------------------------- 1 | using System.IO; 2 | using YamlDotNet.RepresentationModel; 3 | 4 | public class OneYaml { 5 | public static YamlValue load(string content) 6 | { 7 | var yaml = new YamlStream(); 8 | yaml.Load(new StringReader(content)); 9 | return new YamlValue((YamlMappingNode)yaml.Documents[0].RootNode); 10 | } 11 | } -------------------------------------------------------------------------------- /packages/implementations/OneLang-Yaml-v0.1/CSharp/src/YAML.cs: -------------------------------------------------------------------------------- 1 | using System.IO; 2 | using YamlDotNet.Serialization; 3 | using YamlDotNet.Serialization.NamingConventions; 4 | 5 | public class YAML { 6 | public static T safeLoad(string str) { 7 | return new DeserializerBuilder() 8 | .WithNamingConvention(HyphenatedNamingConvention.Instance) 9 | .IgnoreUnmatchedProperties() 10 | .Build() 11 | .Deserialize(new StringReader(str)); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /packages/implementations/OneLang-Yaml-v0.1/Java/src/OneYaml.java: -------------------------------------------------------------------------------- 1 | package io.onelang.std.yaml; 2 | 3 | import org.yaml.snakeyaml.Yaml; 4 | import java.util.Map; 5 | 6 | public class OneYaml { 7 | public static YamlValue load(String content) { 8 | //console.log("loading YAML: '" + content.substring(0, 50).replace("\n", "\\n") + "'"); 9 | Yaml yaml = new Yaml(); 10 | Map obj = yaml.load(content); 11 | //System.out.println(obj); 12 | return new YamlValue(obj); 13 | } 14 | } -------------------------------------------------------------------------------- /packages/implementations/OneLang-Yaml-v0.1/Java/src/ValueType.java: -------------------------------------------------------------------------------- 1 | package io.onelang.std.yaml; 2 | 3 | public enum ValueType { Null, Boolean, Number, String, Array, Object } -------------------------------------------------------------------------------- /packages/implementations/OneLang-Yaml-v0.1/Java/src/YamlValue.java: -------------------------------------------------------------------------------- 1 | package io.onelang.std.yaml; 2 | 3 | import java.util.Map; 4 | import java.util.Arrays; 5 | import java.util.ArrayList; 6 | import java.util.LinkedHashMap; 7 | 8 | public class YamlValue { 9 | public Map map; 10 | 11 | public YamlValue(Map map) { 12 | this.map = map; 13 | } 14 | 15 | public ValueType type() { return ValueType.Null; } 16 | public String asStr() { return null; } 17 | 18 | public YamlValue obj(String key) { 19 | return new YamlValue((Map) this.map.get(key)); 20 | } 21 | 22 | public Double dbl(String key) { 23 | var value = this.map.get(key); 24 | if (value == null) return Double.NaN; 25 | return value instanceof Double ? (Double)value : (double)(int)value; 26 | } 27 | 28 | public String str(String key) { 29 | var value = this.map.get(key); 30 | return value == null ? null : value.toString(); 31 | } 32 | 33 | public YamlValue[] arr(String key) { 34 | var value = this.map.get(key); 35 | if (value == null) return new YamlValue[0]; 36 | return ((ArrayList>) value).stream().map(x -> new YamlValue(x)).toArray(YamlValue[]::new); 37 | } 38 | 39 | public String[] strArr(String key) { 40 | var value = this.map.get(key); 41 | if (value == null) return new String[0]; 42 | return ((ArrayList) value).toArray(String[]::new); 43 | } 44 | 45 | public Map dict(String key) { 46 | var value = this.map.get(key); 47 | var result = new LinkedHashMap(); 48 | if (value != null) 49 | ((Map) value).forEach((k, v) -> 50 | result.put(k, new YamlValue((Map)v))); 51 | return result; 52 | } 53 | } -------------------------------------------------------------------------------- /packages/implementations/OneLang-Yaml-v0.1/PHP/src/OneYaml.php: -------------------------------------------------------------------------------- 1 | value = $value; 18 | } 19 | 20 | function type() { 21 | if (is_null($this->value)) return ValueType::NULL; 22 | if (is_bool($this->value)) return ValueType::BOOLEAN; 23 | if (is_int($this->value) || is_float($this->value)) return ValueType::NUMBER; 24 | if (is_string($this->value)) return ValueType::STRING; 25 | if (is_array($this->value)) return ValueType::ARRAY; 26 | return ValueType::OBJECT; 27 | } 28 | 29 | function asStr() { return $this->value; } 30 | 31 | function dbl($key) { return array_key_exists($key, $this->value) ? $this->value[$key] : 0; } 32 | function str($key) { return array_key_exists($key, $this->value) ? $this->value[$key] : null; } 33 | function strArr($key) { return array_key_exists($key, $this->value) ? $this->value[$key] : []; } 34 | function arr($key) { return array_map(function($x) { return new YamlValue($x); }, $this->value[$key] ?? []); } 35 | function dict($key) { return $this->arr($key); } 36 | function obj($key) { return new YamlValue($this->value[$key]); } 37 | } 38 | 39 | class OneYaml { 40 | static function load($str) { 41 | //print("YAML load -> $str\n"); 42 | return new YamlValue(yaml_parse($str)); 43 | } 44 | } -------------------------------------------------------------------------------- /packages/implementations/OneLang-Yaml-v0.1/Python/src/OneYaml.py: -------------------------------------------------------------------------------- 1 | import yaml 2 | from .YamlValue import YamlValue 3 | 4 | class OneYaml: 5 | @staticmethod 6 | def load(content): 7 | return YamlValue(yaml.safe_load(content)) -------------------------------------------------------------------------------- /packages/implementations/OneLang-Yaml-v0.1/Python/src/YamlValue.py: -------------------------------------------------------------------------------- 1 | from enum import Enum 2 | 3 | class VALUE_TYPE(Enum): 4 | NULL = 0 5 | BOOLEAN = 1 6 | NUMBER = 2 7 | STRING = 3 8 | ARRAY = 4 9 | OBJECT = 5 10 | 11 | class YamlValue: 12 | def __init__(self, value): 13 | self.value = value 14 | 15 | def dbl(self, key): 16 | return self.value.get(key) 17 | 18 | def str(self, key): 19 | return self.value.get(key) 20 | 21 | def str_arr(self, key): 22 | return self.value.get(key) or [] 23 | 24 | def arr(self, key): 25 | return map(lambda x: YamlValue(x), self.value.get(key) or []) 26 | 27 | def obj(self, key): 28 | return YamlValue(self.value.get(key)) 29 | 30 | def dict(self, key): 31 | obj = self.value.get(key) 32 | if obj is None: 33 | return None 34 | 35 | res = {} 36 | for key, value in obj.items(): 37 | res[key] = YamlValue(value) 38 | return res 39 | 40 | def as_str(self): 41 | return str(self.value) 42 | 43 | def type(self): 44 | if self.value is None: 45 | return VALUE_TYPE.NULL 46 | elif isinstance(self.value, bool): 47 | return VALUE_TYPE.BOOLEAN 48 | elif isinstance(self.value, int) or isinstance(self.value, float): 49 | return VALUE_TYPE.NUMBER 50 | elif isinstance(self.value, str): 51 | return VALUE_TYPE.STRING 52 | elif isinstance(self.value, list): 53 | return VALUE_TYPE.ARRAY 54 | else: 55 | return VALUE_TYPE.OBJECT -------------------------------------------------------------------------------- /packages/implementations/OneLang-Yaml-v0.1/Python/src/__init__.py: -------------------------------------------------------------------------------- 1 | from .OneYaml import * 2 | from .YamlValue import * -------------------------------------------------------------------------------- /packages/implementations/OneLang-Yaml-v0.1/package.yaml: -------------------------------------------------------------------------------- 1 | file-version: 1 2 | vendor: OneLang 3 | name: Yaml 4 | version: 0.1 5 | languages: 6 | python: 7 | package-dir: onelang_yaml 8 | native-src-dir: Python/src 9 | native-dependencies: 10 | - { name: PyYAML, version: '5.3.1' } 11 | java: 12 | package-dir: yaml 13 | native-src-dir: Java/src 14 | native-dependencies: 15 | - { name: org.yaml:snakeyaml, version: '1.27' } 16 | csharp: 17 | native-src-dir: CSharp/src 18 | native-dependencies: 19 | - { name: YamlDotNet, version: '8.1.0' } 20 | php: 21 | native-src-dir: PHP/src 22 | -------------------------------------------------------------------------------- /packages/interfaces/One.Ast-v0.1/index.d.ts: -------------------------------------------------------------------------------- 1 | export declare interface IType { 2 | repr(): string; 3 | } -------------------------------------------------------------------------------- /packages/interfaces/One.Ast-v0.1/interface.yaml: -------------------------------------------------------------------------------- 1 | file-version: 1 2 | vendor: One 3 | name: Ast 4 | version: 0.1 5 | definition-file: index.d.ts 6 | 7 | -------------------------------------------------------------------------------- /packages/interfaces/One.BigInteger-v0.1/index.d.ts: -------------------------------------------------------------------------------- 1 | declare class OneBigInteger { 2 | static fromInt(value: number): OneBigInteger; 3 | } 4 | -------------------------------------------------------------------------------- /packages/interfaces/One.BigInteger-v0.1/interface.yaml: -------------------------------------------------------------------------------- 1 | file-version: 1 2 | vendor: One 3 | name: BigInteger 4 | version: 0.1 5 | definition-file: index.d.ts 6 | -------------------------------------------------------------------------------- /packages/interfaces/One.Console-v0.1/index.d.ts: -------------------------------------------------------------------------------- 1 | declare class OneConsole { 2 | static print(str: any): void; 3 | } 4 | -------------------------------------------------------------------------------- /packages/interfaces/One.Console-v0.1/interface.yaml: -------------------------------------------------------------------------------- 1 | file-version: 1 2 | vendor: One 3 | name: Console 4 | version: 0.1 5 | definition-file: index.d.ts 6 | -------------------------------------------------------------------------------- /packages/interfaces/One.Core-v0.1/index.d.ts: -------------------------------------------------------------------------------- 1 | declare class OneArray { 2 | length: number; 3 | add(item: T): void; 4 | get(index: number): T; 5 | set(index: number, value: T): void; 6 | } 7 | 8 | declare class OneMap { 9 | get(key: K): V; 10 | set(key: K, value: V): void; 11 | remove(key: K): void; 12 | 13 | hasKey(key: K): boolean; 14 | 15 | keys(): OneArray; 16 | values(): OneArray; 17 | } 18 | 19 | declare class OneCharacter { 20 | } 21 | 22 | declare class OneString { 23 | length: OneNumber; 24 | substring(start: number, end: number): OneString; 25 | split(separator: string): OneArray; 26 | get(idx: number): OneCharacter; 27 | startsWith(str: string): OneBoolean; 28 | substrMatch(str: string, offset: number): OneBoolean; 29 | replace(from: string, to: string): OneString; 30 | } 31 | 32 | declare class OneNumber { 33 | } 34 | 35 | declare class OneBoolean { 36 | } 37 | 38 | declare class OneError { 39 | static raise(message: string): void; 40 | } 41 | 42 | declare class One { 43 | static langName(): OneString; 44 | } -------------------------------------------------------------------------------- /packages/interfaces/One.Core-v0.1/interface.yaml: -------------------------------------------------------------------------------- 1 | file-version: 1 2 | vendor: One 3 | name: Core 4 | version: 0.1 5 | definition-file: index.d.ts 6 | -------------------------------------------------------------------------------- /packages/interfaces/One.File-v0.1/index.d.ts: -------------------------------------------------------------------------------- 1 | declare class OneFile { 2 | static readText(fn: string): string; 3 | static writeText(fn: string, content: string): void; 4 | static listFiles(dir: string, recursive: boolean): string[]; 5 | static copy(srcFn: string, dstFn: string): void; 6 | } 7 | -------------------------------------------------------------------------------- /packages/interfaces/One.File-v0.1/interface.yaml: -------------------------------------------------------------------------------- 1 | file-version: 1 2 | vendor: One 3 | name: File 4 | version: 0.1 5 | definition-file: index.d.ts 6 | dependencies: 7 | - name: One.Core 8 | minver: 0.1 9 | -------------------------------------------------------------------------------- /packages/interfaces/One.Json-v0.1/index.d.ts: -------------------------------------------------------------------------------- 1 | /// 2 | 3 | export declare class OneJProperty { 4 | getName(): string; 5 | getValue(obj: OneJValue): OneJValue; 6 | } 7 | 8 | export declare class OneJObject { 9 | getProperties(): OneJProperty[]; 10 | count(): number; 11 | names(): string[]; 12 | get(name: string): OneJValue; 13 | } 14 | 15 | export declare class OneJValue { 16 | isObject(): boolean; 17 | isArray(): boolean; 18 | isString(): boolean; 19 | isNumber(): boolean; 20 | isBool(): boolean; 21 | isNull(): boolean; 22 | 23 | asString(): string; 24 | asNumber(): number; 25 | asBool(): boolean; 26 | asObject(): OneJObject; 27 | 28 | getArrayItems(): OneJValue[]; 29 | } 30 | 31 | export declare class OneJson { 32 | static parse(str: string): OneJValue; 33 | static serializeFormatted(obj: any): string; 34 | } 35 | -------------------------------------------------------------------------------- /packages/interfaces/One.Json-v0.1/interface.yaml: -------------------------------------------------------------------------------- 1 | file-version: 1 2 | vendor: One 3 | name: Json 4 | version: 0.1 5 | definition-file: index.d.ts 6 | dependencies: 7 | - name: One.Core 8 | minver: 0.1 9 | -------------------------------------------------------------------------------- /packages/interfaces/One.Reflect-v0.1/index.d.ts: -------------------------------------------------------------------------------- 1 | import { IType } from "One.Ast-v0.1"; 2 | 3 | export declare class ReflectedValue { 4 | getField(name: string): ReflectedValue; 5 | getArrayItems(): ReflectedValue[]; 6 | getMapKeys(): string[]; 7 | getMapValue(key: string): ReflectedValue; 8 | getEnumValueAsString(): string; 9 | getBooleanValue(): boolean; 10 | getStringValue(): string; 11 | isNull(): boolean; 12 | getUniqueIdentifier(): any; 13 | getValueType(): IType; 14 | getDeclaredType(): IType; 15 | } 16 | -------------------------------------------------------------------------------- /packages/interfaces/One.Reflect-v0.1/interface.yaml: -------------------------------------------------------------------------------- 1 | file-version: 1 2 | vendor: One 3 | name: Reflect 4 | version: 0.1 5 | definition-file: index.d.ts 6 | dependencies: 7 | - name: One.Ast 8 | minver: 0.1 9 | -------------------------------------------------------------------------------- /packages/interfaces/One.Regex-v0.1/index.d.ts: -------------------------------------------------------------------------------- 1 | declare class OneRegex { 2 | static matchFromIndex(pattern: string, input: string, offset: number): string[]; 3 | } 4 | -------------------------------------------------------------------------------- /packages/interfaces/One.Regex-v0.1/interface.yaml: -------------------------------------------------------------------------------- 1 | file-version: 1 2 | vendor: One 3 | name: Regex 4 | version: 0.1 5 | definition-file: index.d.ts 6 | dependencies: 7 | - name: One.Core 8 | minver: 0.1 9 | -------------------------------------------------------------------------------- /packages/interfaces/One.Yaml-v0.1/index.d.ts: -------------------------------------------------------------------------------- 1 | export declare enum ValueType { Null, Boolean, Number, String, Array, Object } 2 | 3 | export declare class YamlValue { 4 | type(): ValueType; 5 | asStr(): string; 6 | 7 | obj(key: string): YamlValue; 8 | dbl(key: string): number; 9 | str(key: string): string; 10 | arr(key: string): YamlValue[]; 11 | dict(key: string): { [name: string]: YamlValue }; 12 | strArr(key: string): string[]; 13 | } 14 | 15 | export declare class OneYaml { 16 | static load(content: string): YamlValue; 17 | } -------------------------------------------------------------------------------- /packages/interfaces/One.Yaml-v0.1/interface.yaml: -------------------------------------------------------------------------------- 1 | file-version: 1 2 | vendor: One 3 | name: Yaml 4 | version: 0.1 5 | definition-file: index.d.ts 6 | dependencies: 7 | - name: One.Yaml 8 | minver: 0.1 9 | -------------------------------------------------------------------------------- /project-templates/One.CSharp-v1/index.yaml: -------------------------------------------------------------------------------- 1 | language: csharp 2 | package-dir: OnePackages 3 | template-files: [CSharp.csproj] 4 | -------------------------------------------------------------------------------- /project-templates/One.CSharp-v1/src/.gitignore: -------------------------------------------------------------------------------- 1 | bin/ 2 | obj/ -------------------------------------------------------------------------------- /project-templates/One.CSharp-v1/src/.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "name": ".NET Core Launch (console)", 9 | "type": "coreclr", 10 | "request": "launch", 11 | "preLaunchTask": "build", 12 | "program": "${workspaceFolder}/bin/Debug/netcoreapp3.0/CSharp.dll", 13 | "args": [], 14 | "cwd": "${workspaceFolder}", 15 | "console": "internalConsole", 16 | "stopAtEntry": false 17 | }, 18 | { 19 | "name": ".NET Core Attach", 20 | "type": "coreclr", 21 | "request": "attach", 22 | "processId": "${command:pickProcess}" 23 | } 24 | ] 25 | } -------------------------------------------------------------------------------- /project-templates/One.CSharp-v1/src/.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "2.0.0", 3 | "tasks": [ 4 | { 5 | "label": "build", 6 | "command": "dotnet", 7 | "type": "process", 8 | "args": [ 9 | "build", 10 | "${workspaceFolder}/CSharp.csproj", 11 | "/property:GenerateFullPaths=true", 12 | "/consoleloggerparameters:NoSummary" 13 | ], 14 | "problemMatcher": "$msCompile" 15 | }, 16 | { 17 | "label": "publish", 18 | "command": "dotnet", 19 | "type": "process", 20 | "args": [ 21 | "publish", 22 | "${workspaceFolder}/CSharp.csproj", 23 | "/property:GenerateFullPaths=true", 24 | "/consoleloggerparameters:NoSummary" 25 | ], 26 | "problemMatcher": "$msCompile" 27 | }, 28 | { 29 | "label": "watch", 30 | "command": "dotnet", 31 | "type": "process", 32 | "args": [ 33 | "watch", 34 | "run", 35 | "${workspaceFolder}/CSharp.csproj", 36 | "/property:GenerateFullPaths=true", 37 | "/consoleloggerparameters:NoSummary" 38 | ], 39 | "problemMatcher": "$msCompile" 40 | } 41 | ] 42 | } -------------------------------------------------------------------------------- /project-templates/One.CSharp-v1/src/CSharp.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | netcoreapp3.0 6 | 7 | 8 | 9 | {{for dep of dependencies}} 10 | 11 | {{/for}} 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /project-templates/One.Java-v1/index.yaml: -------------------------------------------------------------------------------- 1 | language: java 2 | package-dir: src/main/java/io/onelang/std 3 | template-files: [build.gradle] 4 | -------------------------------------------------------------------------------- /project-templates/One.Java-v1/src/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /project-templates/One.Java-v1/src/.gitattributes: -------------------------------------------------------------------------------- 1 | # 2 | # https://help.github.com/articles/dealing-with-line-endings/ 3 | # 4 | # These are explicitly windows files and should use crlf 5 | *.bat text eol=crlf 6 | 7 | -------------------------------------------------------------------------------- /project-templates/One.Java-v1/src/.gitignore: -------------------------------------------------------------------------------- 1 | # Ignore Gradle project-specific cache directory 2 | .gradle 3 | 4 | # Ignore Gradle build output directory 5 | build -------------------------------------------------------------------------------- /project-templates/One.Java-v1/src/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | Java 4 | Project Java created by Buildship. 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | org.eclipse.buildship.core.gradleprojectbuilder 15 | 16 | 17 | 18 | 19 | 20 | org.eclipse.jdt.core.javanature 21 | org.eclipse.buildship.core.gradleprojectnature 22 | 23 | 24 | 25 | 1605371545023 26 | 27 | 30 28 | 29 | org.eclipse.core.resources.regexFilterMatcher 30 | node_modules|.git|__CREATED_BY_JAVA_LANGUAGE_SERVER__ 31 | 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /project-templates/One.Java-v1/src/.settings/org.eclipse.buildship.core.prefs: -------------------------------------------------------------------------------- 1 | arguments= 2 | auto.sync=false 3 | build.scans.enabled=false 4 | connection.gradle.distribution=GRADLE_DISTRIBUTION(WRAPPER) 5 | connection.project.dir= 6 | eclipse.preferences.version=1 7 | gradle.user.home= 8 | java.home=/Library/Java/JavaVirtualMachines/adoptopenjdk-11.jdk/Contents/Home 9 | jvm.arguments= 10 | offline.mode=false 11 | override.workspace.settings=true 12 | show.console.view=true 13 | show.executions.view=true 14 | -------------------------------------------------------------------------------- /project-templates/One.Java-v1/src/.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "0.2.0", 3 | "configurations": [ 4 | { 5 | "type": "java", 6 | "name": "Debug (Launch)", 7 | "request": "launch", 8 | "cwd": "${workspaceFolder}", 9 | "console": "internalConsole", 10 | "stopOnEntry": false, 11 | "preLaunchTask": "compileJava", 12 | "mainClass": "Main", 13 | "args": "" 14 | } 15 | ] 16 | } -------------------------------------------------------------------------------- /project-templates/One.Java-v1/src/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "java.configuration.updateBuildConfiguration": "automatic", 3 | "java.errors.incompleteClasspath.severity": "ignore", 4 | "java.import.gradle.enabled": true, 5 | "files.exclude": { 6 | "**/.classpath": true, 7 | "**/.project": true, 8 | "**/.settings": true, 9 | "**/.factorypath": true 10 | } 11 | } -------------------------------------------------------------------------------- /project-templates/One.Java-v1/src/.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "2.0.0", 3 | "echoCommand": true, 4 | "command": "./gradlew", 5 | "presentation": { 6 | "echo": true, 7 | "reveal": "always", 8 | "focus": false, 9 | "panel": "shared" 10 | }, 11 | "tasks": [ 12 | { 13 | "label": "compileJava", 14 | "type": "shell" 15 | }, 16 | { 17 | "label": "processResources", 18 | "type": "shell" 19 | }, 20 | { 21 | "label": "classes", 22 | "type": "shell" 23 | }, 24 | { 25 | "label": "processTestResources", 26 | "type": "shell" 27 | }, 28 | { 29 | "label": "jar", 30 | "type": "shell" 31 | }, 32 | { 33 | "label": "javadoc", 34 | "type": "shell" 35 | }, 36 | { 37 | "label": "test", 38 | "type": "shell", 39 | "group": { 40 | "kind": "test", 41 | "isDefault": true 42 | } 43 | }, 44 | { 45 | "label": "uploadArchibes", 46 | "type": "shell" 47 | }, 48 | { 49 | "label": "clean", 50 | "type": "shell" 51 | }, 52 | { 53 | "label": "assemble", 54 | "type": "shell" 55 | }, 56 | { 57 | "label": "check", 58 | "type": "shell" 59 | }, 60 | { 61 | "label": "build", 62 | "type": "shell", 63 | "group": { 64 | "kind": "build", 65 | "isDefault": true 66 | } 67 | }, 68 | { 69 | "label": "buildNeeded", 70 | "type": "shell" 71 | }, 72 | { 73 | "label": "buildDependents", 74 | "type": "shell" 75 | } 76 | ] 77 | } -------------------------------------------------------------------------------- /project-templates/One.Java-v1/src/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'java' 2 | apply plugin: 'application' 3 | mainClassName = 'Main' 4 | 5 | repositories { 6 | mavenCentral() 7 | } 8 | 9 | dependencies { 10 | {{for dep of dependencies}} 11 | implementation '{{dep.name}}:{{dep.version}}' 12 | {{/for}} 13 | } -------------------------------------------------------------------------------- /project-templates/One.Java-v1/src/gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/00mjk/OneLang/0e6627bced4426a34d560159326b31f41f8a74ac/project-templates/One.Java-v1/src/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /project-templates/One.Java-v1/src/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.6.1-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /project-templates/One.Java-v1/src/settings.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * This file was generated by the Gradle 'init' task. 3 | * 4 | * The settings file is used to specify which projects to include in your build. 5 | * 6 | * Detailed information about configuring a multi-project build in Gradle can be found 7 | * in the user manual at https://docs.gradle.org/6.6.1/userguide/multi_project_builds.html 8 | */ 9 | 10 | rootProject.name = 'Java' 11 | -------------------------------------------------------------------------------- /project-templates/One.PHP-v1/index.yaml: -------------------------------------------------------------------------------- 1 | language: php 2 | destination-dir: src 3 | package-dir: onepkg 4 | template-files: [composer.json] -------------------------------------------------------------------------------- /project-templates/One.PHP-v1/src/OneLoader.php: -------------------------------------------------------------------------------- 1 | $fileName.php\n"); 13 | else 14 | require_once("$fileName.php"); 15 | }); 16 | } 17 | } 18 | OneLoader::init(); 19 | -------------------------------------------------------------------------------- /project-templates/One.PHP-v1/src/composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "autoload": { 3 | "psr-4": { 4 | {{for pkg of onepackages, joiner=","}} 5 | "{{pkg.vendor}}\\{{pkg.id}}\\": "onepkg/{{pkg.vendor}}-{{pkg.id}}" 6 | {{/for}} 7 | } 8 | } 9 | } -------------------------------------------------------------------------------- /project-templates/One.Python-v1/index.yaml: -------------------------------------------------------------------------------- 1 | language: python 2 | package-dir: onepkg 3 | template-files: [requirements.txt] 4 | -------------------------------------------------------------------------------- /project-templates/One.Python-v1/src/.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc -------------------------------------------------------------------------------- /project-templates/One.Python-v1/src/.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "name": "Python: Current File", 9 | "type": "python", 10 | "request": "launch", 11 | "program": "${workspaceFolder}/main.py", 12 | "console": "integratedTerminal" 13 | } 14 | ] 15 | } -------------------------------------------------------------------------------- /project-templates/One.Python-v1/src/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/00mjk/OneLang/0e6627bced4426a34d560159326b31f41f8a74ac/project-templates/One.Python-v1/src/__init__.py -------------------------------------------------------------------------------- /project-templates/One.Python-v1/src/requirements.txt: -------------------------------------------------------------------------------- 1 | {{for dep of dependencies}} 2 | {{dep.name}}=={{dep.version}} 3 | {{/for}} -------------------------------------------------------------------------------- /src/Generator/GeneratedFile.ts: -------------------------------------------------------------------------------- 1 | export class GeneratedFile { 2 | constructor(public path: string, public content: string) { } 3 | } 4 | -------------------------------------------------------------------------------- /src/Generator/IGenerator.ts: -------------------------------------------------------------------------------- 1 | import { GeneratedFile } from "./GeneratedFile"; 2 | import { Package } from "../One/Ast/Types"; 3 | import { ITransformer } from "../One/ITransformer"; 4 | import { IGeneratorPlugin } from "./IGeneratorPlugin"; 5 | import { IExpression } from "../One/Ast/Interfaces"; 6 | 7 | export interface IGenerator { 8 | getLangName(): string; 9 | getExtension(): string; 10 | getTransforms(): ITransformer[]; 11 | addPlugin(plugin: IGeneratorPlugin): void; 12 | addInclude(include: string): void; 13 | expr(expr: IExpression): string; 14 | generate(pkg: Package): GeneratedFile[]; 15 | } -------------------------------------------------------------------------------- /src/Generator/IGeneratorPlugin.ts: -------------------------------------------------------------------------------- 1 | import { IExpression } from "../One/Ast/Interfaces"; 2 | import { Statement } from "../One/Ast/Statements"; 3 | 4 | export interface IGeneratorPlugin { 5 | expr(expr: IExpression): string; 6 | stmt(stmt: Statement): string; 7 | } -------------------------------------------------------------------------------- /src/Generator/NameUtils.ts: -------------------------------------------------------------------------------- 1 | export class NameUtils { 2 | static shortName(fullName: string): string { 3 | const nameParts: string[] = []; 4 | let partStartIdx = 0; 5 | for (let i = 1; i < fullName.length; i++) { 6 | const chrCode = fullName.charCodeAt(i); 7 | const chrIsUpper = 65 <= chrCode && chrCode <= 90; 8 | if (chrIsUpper) { 9 | nameParts.push(fullName.substring(partStartIdx, i)); 10 | partStartIdx = i; 11 | } 12 | } 13 | nameParts.push(fullName.substr(partStartIdx)); 14 | 15 | const shortNameParts: string[] = []; 16 | for (let i = 0; i < nameParts.length; i++) { 17 | let p = nameParts[i]; 18 | if (p.length > 5) { 19 | let cutPoint = 3; 20 | for (; cutPoint <= 4; cutPoint++) 21 | if ("aeoiu".includes(p[cutPoint])) 22 | break; 23 | p = p.substr(0, cutPoint); 24 | } 25 | shortNameParts.push(i === 0 ? p.toLowerCase() : p); 26 | } 27 | 28 | let shortName = shortNameParts.join(''); 29 | if (fullName.endsWith("s") && !shortName.endsWith("s")) 30 | shortName += "s"; 31 | return shortName; 32 | } 33 | } -------------------------------------------------------------------------------- /src/One/Ast/AstHelper.ts: -------------------------------------------------------------------------------- 1 | import { IInterface, Class } from "./Types"; 2 | import { InterfaceType, ClassType } from "./AstTypes"; 3 | 4 | export class AstHelper { 5 | static collectAllBaseInterfaces(intf: IInterface): IInterface[] { 6 | const result = new Set(); 7 | const toBeProcessed: IInterface[] = [intf]; 8 | 9 | while (toBeProcessed.length > 0) { 10 | const curr = toBeProcessed.pop(); 11 | result.add(curr); 12 | 13 | if (curr instanceof Class && curr.baseClass !== null) 14 | toBeProcessed.push(( curr.baseClass).decl); 15 | 16 | for (const baseIntf of curr.baseInterfaces) 17 | toBeProcessed.push(( baseIntf).decl); 18 | } 19 | 20 | return Array.from(result.values()); 21 | } 22 | } -------------------------------------------------------------------------------- /src/One/Ast/Interfaces.ts: -------------------------------------------------------------------------------- 1 | export interface IType { 2 | repr(): string; 3 | } 4 | 5 | export interface IExpression { 6 | setActualType(actualType: IType, allowVoid: boolean, allowGeneric: boolean): void; 7 | setExpectedType(type: IType, allowVoid: boolean): void; 8 | getType(): IType; 9 | } 10 | -------------------------------------------------------------------------------- /src/One/CompilerHelper.ts: -------------------------------------------------------------------------------- 1 | // @python-import-all onelang_file 2 | // @php-use OneLang\File\OneFile 3 | import { OneFile } from "One.File-v0.1"; 4 | import { Compiler } from "./Compiler"; 5 | 6 | export class CompilerHelper { 7 | static baseDir: string = "./"; 8 | 9 | static async initProject(projectName: string, sourceDir: string, lang: string = "ts", packagesDir: string = null): Promise { 10 | if (lang !== "ts") throw new Error("Only typescript is supported."); 11 | 12 | const compiler = new Compiler(); 13 | await compiler.init(packagesDir || `${this.baseDir}packages/`); 14 | compiler.setupNativeResolver(OneFile.readText(`${this.baseDir}langs/NativeResolvers/typescript.ts`)); 15 | compiler.newWorkspace(projectName); 16 | 17 | for (const file of OneFile.listFiles(sourceDir, true).filter(x => x.endsWith(".ts"))) 18 | compiler.addProjectFile(file, OneFile.readText(`${sourceDir}/${file}`)); 19 | 20 | return compiler; 21 | } 22 | } -------------------------------------------------------------------------------- /src/One/ITransformer.ts: -------------------------------------------------------------------------------- 1 | import { SourceFile } from "./Ast/Types"; 2 | 3 | export interface ITransformer { 4 | name: string; 5 | visitFiles(files: SourceFile[]): void; 6 | } -------------------------------------------------------------------------------- /src/One/Transforms/CollectInheritanceInfo.ts: -------------------------------------------------------------------------------- 1 | import { Package, Class, Interface, SourceFile } from "../Ast/Types"; 2 | import { ITransformer } from "../ITransformer"; 3 | 4 | export class CollectInheritanceInfo implements ITransformer { 5 | name = "CollectInheritanceInfo"; 6 | 7 | constructor() { 8 | // C# fix 9 | this.name = "CollectInheritanceInfo"; 10 | } 11 | 12 | visitClass(cls: Class) { 13 | const allBaseIIntfs = cls.getAllBaseInterfaces(); 14 | const intfs = allBaseIIntfs.map(x => x instanceof Interface ? x : null).filter(x => x !== null); 15 | const clses = allBaseIIntfs.map(x => x instanceof Class ? x : null).filter(x => x !== null && x !== cls); 16 | 17 | for (const field of cls.fields) 18 | field.interfaceDeclarations = intfs.map(x => x.fields.find(f => f.name === field.name) || null).filter(x => x !== null); 19 | 20 | for (const method of cls.methods) { 21 | method.interfaceDeclarations = intfs.map(x => x.methods.find(m => m.name === method.name) || null).filter(x => x !== null); 22 | method.overrides = clses.map(x => x.methods.find(m => m.name === method.name) || null).find(x => x !== null) || null; 23 | if (method.overrides !== null) 24 | method.overrides.overriddenBy.push(method); 25 | } 26 | } 27 | 28 | visitFiles(files: SourceFile[]) { 29 | for (const file of files) 30 | for (const cls of file.classes) 31 | this.visitClass(cls); 32 | } 33 | } -------------------------------------------------------------------------------- /src/One/Transforms/ConvertToMethodCall.ts: -------------------------------------------------------------------------------- 1 | import { Expression, ElementAccessExpression, UnresolvedCallExpression, PropertyAccessExpression, BinaryExpression, StringLiteral } from "../Ast/Expressions"; 2 | import { AstTransformer } from "../AstTransformer"; 3 | 4 | /** 5 | * Converts "key in obj" to "obj.hasKey(key)" 6 | */ 7 | export class ConvertToMethodCall extends AstTransformer { 8 | constructor() { super("ConvertToMethodCall"); } 9 | 10 | protected visitExpression(expr: Expression) { 11 | const origExpr = expr; 12 | 13 | expr = super.visitExpression(expr); 14 | 15 | if (expr instanceof BinaryExpression && expr.operator === "in") 16 | expr = new UnresolvedCallExpression(new PropertyAccessExpression(expr.right, "hasKey"), [], [expr.left]); 17 | 18 | expr.parentNode = origExpr.parentNode; 19 | return expr; 20 | } 21 | } -------------------------------------------------------------------------------- /src/One/Transforms/DetectMethodCalls.ts: -------------------------------------------------------------------------------- 1 | import { AstTransformer } from "../AstTransformer"; 2 | import { Expression, UnresolvedCallExpression, PropertyAccessExpression, UnresolvedMethodCallExpression } from "../Ast/Expressions"; 3 | 4 | /** 5 | * Converts "obj.method(args)" from a generic "func(args)"-style call to a method call of the "method" method on the "obj" object with "args" arguments 6 | */ 7 | export class DetectMethodCalls extends AstTransformer { 8 | constructor() { super("DetectMethodCalls"); } 9 | 10 | protected visitExpression(expr: Expression): Expression { 11 | expr = super.visitExpression(expr); 12 | if (expr instanceof UnresolvedCallExpression && expr.func instanceof PropertyAccessExpression) 13 | return new UnresolvedMethodCallExpression(expr.func.object, expr.func.propertyName, expr.typeArgs, expr.args); 14 | return expr; 15 | } 16 | } -------------------------------------------------------------------------------- /src/One/Transforms/FillAttributesFromTrivia.ts: -------------------------------------------------------------------------------- 1 | import { SourceFile, IMethodBase, IHasAttributesAndTrivia, Package, IMethodBaseWithTrivia } from "../Ast/Types"; 2 | import { ForeachStatement, ForStatement, IfStatement, Block, WhileStatement, DoStatement } from "../Ast/Statements"; 3 | import { AstTransformer } from "../AstTransformer"; 4 | import { Expression } from "../Ast/Expressions"; 5 | 6 | /** 7 | * Extract `@attributeName attribute value` attributes from comments (// and /* style comments) 8 | */ 9 | export class FillAttributesFromTrivia extends AstTransformer { 10 | constructor() { super("FillAttributesFromTrivia"); } 11 | 12 | protected visitAttributesAndTrivia(node: IHasAttributesAndTrivia) { 13 | node.attributes = FillAttributesFromTrivia.processTrivia(node.leadingTrivia); 14 | } 15 | 16 | // optimization 17 | protected visitExpression(expr: Expression): Expression { return expr; } 18 | 19 | static processTrivia(trivia: string): { [name: string]: string } { 20 | const result: { [name: string]: string } = {}; 21 | if (trivia !== null && trivia !== "") { 22 | const regex = /(?:\n|^)\s*(?:\/\/|#|\/\*\*?)\s*@([A-Za-z0-9_.-]+) ?((?!\n|\*\/|$).+)?/g; 23 | while(true) { 24 | const match = regex.exec(trivia) || null; 25 | if (match === null) break; 26 | if (match[1] in result) 27 | // @php $result[$match[1]] .= "\n" . $match[2]; 28 | // @python result[match[1]] += "\n" + match[2] 29 | // @csharp result[match[1]] += "\n" + match[2]; 30 | // @java result.put(match[1], result.get(match[1]) + "\n" + match[2]); 31 | result[match[1]] += "\n" + match[2]; 32 | else 33 | result[match[1]] = (match[2] || "") === "" ? "true" : match[2] || ""; 34 | } 35 | } 36 | return result; 37 | } 38 | } -------------------------------------------------------------------------------- /src/One/Transforms/InferTypesPlugins/Helpers/InferTypesPlugin.ts: -------------------------------------------------------------------------------- 1 | import { ErrorManager } from "../../../ErrorManager"; 2 | import { Expression } from "../../../Ast/Expressions"; 3 | import { InferTypes } from "../../InferTypes"; 4 | import { Statement } from "../../../Ast/Statements"; 5 | import { Property, Lambda, Method, IMethodBase } from "../../../Ast/Types"; 6 | 7 | export class InferTypesPlugin { 8 | main: InferTypes; 9 | errorMan: ErrorManager = null; 10 | 11 | constructor(public name: string) { } 12 | 13 | canTransform(expr: Expression): boolean { return false; } 14 | canDetectType(expr: Expression): boolean { return false; } 15 | 16 | transform(expr: Expression): Expression { return expr; } 17 | detectType(expr: Expression): boolean { return false; } 18 | 19 | handleProperty(prop: Property): boolean { return false; } 20 | handleLambda(lambda: Lambda): boolean { return false; } 21 | handleMethod(method: IMethodBase): boolean { return false; } 22 | handleStatement(stmt: Statement): boolean { return false; } 23 | } 24 | -------------------------------------------------------------------------------- /src/One/Transforms/InferTypesPlugins/InferForeachVarType.ts: -------------------------------------------------------------------------------- 1 | import { InferTypesPlugin } from "./Helpers/InferTypesPlugin"; 2 | import { ClassType, InterfaceType, IInterfaceType, AnyType } from "../../Ast/AstTypes"; 3 | import { Statement, ForeachStatement } from "../../Ast/Statements"; 4 | 5 | export class InferForeachVarType extends InferTypesPlugin { 6 | constructor() { super("InferForeachVarType"); } 7 | 8 | handleStatement(stmt: Statement) { 9 | if (stmt instanceof ForeachStatement) { 10 | stmt.items = this.main.runPluginsOn(stmt.items); 11 | const arrayType = stmt.items.getType(); 12 | let found = false; 13 | if (arrayType instanceof ClassType || arrayType instanceof InterfaceType) { 14 | const intfType = arrayType; 15 | const isArrayType = this.main.currentFile.arrayTypes.some(x => x.decl === intfType.getDecl()); 16 | if (isArrayType && intfType.typeArguments.length > 0) { 17 | stmt.itemVar.type = intfType.typeArguments[0]; 18 | found = true; 19 | } 20 | } 21 | 22 | if (!found && !(arrayType instanceof AnyType)) 23 | this.errorMan.throw(`Expected array as Foreach items variable, but got ${arrayType.repr()}`); 24 | 25 | this.main.processBlock(stmt.body); 26 | return true; 27 | } 28 | return false; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/One/Transforms/InferTypesPlugins/LambdaResolver.ts: -------------------------------------------------------------------------------- 1 | import { InferTypesPlugin } from "./Helpers/InferTypesPlugin"; 2 | import { Expression } from "../../Ast/Expressions"; 3 | import { Lambda } from "../../Ast/Types"; 4 | import { LambdaType, TypeHelper } from "../../Ast/AstTypes"; 5 | 6 | export class LambdaResolver extends InferTypesPlugin { 7 | constructor() { super("LambdaResolver"); } 8 | 9 | protected setupLambdaParameterTypes(lambda: Lambda) { 10 | if (lambda.expectedType === null) return; 11 | 12 | if (lambda.expectedType instanceof LambdaType) { 13 | const declParams = lambda.expectedType.parameters; 14 | if (declParams.length !== lambda.parameters.length) 15 | this.errorMan.throw(`Expected ${lambda.parameters.length} parameters for lambda, but got ${declParams.length}!`); 16 | else { 17 | for (let i = 0; i < declParams.length; i++) { 18 | if (lambda.parameters[i].type === null) 19 | lambda.parameters[i].type = declParams[i].type; 20 | else if (!TypeHelper.isAssignableTo(lambda.parameters[i].type, declParams[i].type)) 21 | this.errorMan.throw(`Parameter type ${lambda.parameters[i].type.repr()} cannot be assigned to ${declParams[i].type.repr()}.`); 22 | } 23 | } 24 | } else 25 | this.errorMan.throw("Expected LambdaType as Lambda's type!"); 26 | } 27 | 28 | protected visitLambda(lambda: Lambda): void { 29 | this.setupLambdaParameterTypes(lambda); 30 | //this.main.visitLambda(lambda); 31 | } 32 | 33 | canTransform(expr: Expression) { return expr instanceof Lambda; } 34 | 35 | transform(expr: Expression): Expression { 36 | this.visitLambda( expr); 37 | // does not transform actually 38 | return expr; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/One/Transforms/InferTypesPlugins/NullabilityCheckWithNot.ts: -------------------------------------------------------------------------------- 1 | import { InferTypesPlugin } from "./Helpers/InferTypesPlugin"; 2 | import { Expression, UnaryExpression, BinaryExpression, NullLiteral } from "../../Ast/Expressions"; 3 | import { ClassType } from "../../Ast/AstTypes"; 4 | 5 | // converts "!SomeObject" to "SomeObject === null" 6 | export class NullabilityCheckWithNot extends InferTypesPlugin { 7 | constructor() { super("NullabilityCheckWithNot"); } 8 | 9 | canTransform(expr: Expression) { return expr instanceof UnaryExpression ? expr.operator === "!" : false; } 10 | 11 | transform(expr: Expression): Expression { 12 | const unaryExpr = expr; 13 | if (unaryExpr.operator === "!") { 14 | this.main.processExpression(expr); 15 | const type = unaryExpr.operand.actualType; 16 | const litTypes = this.main.currentFile.literalTypes; 17 | if (type instanceof ClassType && type.decl !== litTypes.boolean.decl && type.decl !== litTypes.numeric.decl) 18 | return new BinaryExpression(unaryExpr.operand, "==", new NullLiteral()); 19 | } 20 | 21 | return expr; 22 | } 23 | } -------------------------------------------------------------------------------- /src/One/Transforms/InferTypesPlugins/ResolveEnumMemberAccess.ts: -------------------------------------------------------------------------------- 1 | import { InferTypesPlugin } from "./Helpers/InferTypesPlugin"; 2 | import { Expression, PropertyAccessExpression } from "../../Ast/Expressions"; 3 | import { EnumMemberReference, EnumReference } from "../../Ast/References"; 4 | 5 | export class ResolveEnumMemberAccess extends InferTypesPlugin { 6 | constructor() { super("ResolveEnumMemberAccess"); } 7 | 8 | canTransform(expr: Expression) { return expr instanceof PropertyAccessExpression && expr.object instanceof EnumReference; } 9 | 10 | transform(expr: Expression): Expression { 11 | const pa = expr; 12 | const enumMemberRef = pa.object; 13 | const member = enumMemberRef.decl.values.find(x => x.name === pa.propertyName) || null; 14 | if (member === null) { 15 | this.errorMan.throw(`Enum member was not found: ${enumMemberRef.decl.name}::${pa.propertyName}`); 16 | return expr; 17 | } 18 | return new EnumMemberReference(member); 19 | } 20 | 21 | canDetectType(expr: Expression) { return expr instanceof EnumMemberReference; } 22 | 23 | detectType(expr: Expression) { 24 | expr.setActualType((expr).decl.parentEnum.type); 25 | return true; 26 | } 27 | } -------------------------------------------------------------------------------- /src/One/Transforms/InferTypesPlugins/ResolveFuncCalls.ts: -------------------------------------------------------------------------------- 1 | import { InferTypesPlugin } from "./Helpers/InferTypesPlugin"; 2 | import { Expression, UnresolvedCallExpression, GlobalFunctionCallExpression, LambdaCallExpression } from "../../Ast/Expressions"; 3 | import { GlobalFunctionReference } from "../../Ast/References"; 4 | import { LambdaType } from "../../Ast/AstTypes"; 5 | 6 | // converts `parseInt(...)` -> UnresolvedCallExpression(GlobalFunctionReference) to GlobalFunctionCallExpression 7 | // converts `someLambda(...)` -> UnresolvedCallExpression(variable[LambdaType]) to LambdaCallExpression 8 | export class ResolveFuncCalls extends InferTypesPlugin { 9 | constructor() { super("ResolveFuncCalls"); } 10 | 11 | canTransform(expr: Expression) { return expr instanceof UnresolvedCallExpression; } 12 | 13 | transform(expr: Expression): Expression { 14 | const callExpr = expr; 15 | if (callExpr.func instanceof GlobalFunctionReference) { 16 | const newExpr = new GlobalFunctionCallExpression(callExpr.func.decl, callExpr.args); 17 | callExpr.args = callExpr.args.map(arg => this.main.runPluginsOn(arg)); 18 | newExpr.setActualType(callExpr.func.decl.returns); 19 | return newExpr; 20 | } else { 21 | this.main.processExpression(expr); 22 | if (callExpr.func.actualType instanceof LambdaType) { 23 | const newExpr = new LambdaCallExpression(callExpr.func, callExpr.args); 24 | newExpr.setActualType(callExpr.func.actualType.returnType); 25 | return newExpr; 26 | } else { 27 | debugger; 28 | return expr; 29 | } 30 | } 31 | } 32 | } -------------------------------------------------------------------------------- /src/One/Transforms/InferTypesPlugins/ResolveNewCall.ts: -------------------------------------------------------------------------------- 1 | import { InferTypesPlugin } from "./Helpers/InferTypesPlugin"; 2 | import { Expression, NewExpression } from "../../Ast/Expressions"; 3 | 4 | // handles `new SomeObject(...)` 5 | export class ResolveNewCalls extends InferTypesPlugin { 6 | constructor() { super("ResolveNewCalls"); } 7 | 8 | canTransform(expr: Expression) { return expr instanceof NewExpression; } 9 | 10 | transform(expr: Expression): Expression { 11 | const newExpr = expr; 12 | for (let i = 0; i < newExpr.args.length; i++) { 13 | newExpr.args[i].setExpectedType(newExpr.cls.decl.constructor_.parameters[i].type); 14 | newExpr.args[i] = this.main.runPluginsOn(newExpr.args[i]); 15 | } 16 | expr.setActualType(newExpr.cls); 17 | return expr; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/One/Transforms/ResolveGenericTypeIdentifiers.ts: -------------------------------------------------------------------------------- 1 | import { AstTransformer } from "../AstTransformer"; 2 | import { UnresolvedType, GenericsType } from "../Ast/AstTypes"; 3 | import { Class, Method } from "../Ast/Types"; 4 | import { IType } from "../Ast/Interfaces"; 5 | 6 | /** 7 | * After parsing an input source code file, it is not known that a "T" is 8 | * an unknown type called "T" or it is a generic type, as it only turns 9 | * out when a class or method is flagged with in its declaration. 10 | * 11 | * So this tranform modifies "T" from (unknown) type "T" to generic type "T" 12 | * in classes "ExampleClass { ... T ... }" 13 | * and methods "ExampleMethod(...) { ... T ... }" 14 | */ 15 | export class ResolveGenericTypeIdentifiers extends AstTransformer { 16 | constructor() { super("ResolveGenericTypeIdentifiers"); } 17 | 18 | protected visitType(type: IType): IType { 19 | super.visitType(type); 20 | 21 | //console.log(type && type.constructor.name, JSON.stringify(type)); 22 | if (type instanceof UnresolvedType && 23 | ((this.currentInterface instanceof Class && this.currentInterface.typeArguments.includes(type.typeName)) || 24 | (this.currentMethod instanceof Method && this.currentMethod.typeArguments.includes(type.typeName)))) 25 | return new GenericsType(type.typeName); 26 | 27 | return type; 28 | } 29 | } -------------------------------------------------------------------------------- /src/One/Transforms/ResolveImports.ts: -------------------------------------------------------------------------------- 1 | import { Workspace, UnresolvedImport, SourceFile, Package } from "../Ast/Types"; 2 | import { AstTransformer } from "../AstTransformer"; 3 | 4 | /** 5 | * Fills SourceFile's `availableSymbols` property with all the imported symbols. 6 | * Also replaces UnresolvedImports in `Import.imports` to an IImportable (either Interface or Class or GlobalFunction) 7 | */ 8 | export class ResolveImports extends AstTransformer { 9 | constructor(public workspace: Workspace) { super("ResolveImports"); } 10 | 11 | public visitFile(sourceFile: SourceFile): void { 12 | ResolveImports.processFile(this.workspace, sourceFile); 13 | } 14 | 15 | static processFile(ws: Workspace, file: SourceFile): void { 16 | for (const imp of file.imports) { 17 | const impPkg = ws.getPackage(imp.exportScope.packageName); 18 | const scope = impPkg.getExportedScope(imp.exportScope.scopeName); 19 | imp.imports = imp.importAll ? scope.getAllExports() : 20 | imp.imports.map(x => x instanceof UnresolvedImport ? scope.getExport(x.name) : x); 21 | file.addAvailableSymbols(imp.imports); 22 | } 23 | } 24 | 25 | static processWorkspace(ws: Workspace): void { 26 | for (const pkg of Object.values(ws.packages)) 27 | for (const file of Object.values(pkg.files)) 28 | this.processFile(ws, file); 29 | } 30 | } -------------------------------------------------------------------------------- /src/One/Transforms/UseDefaultCallArgsExplicitly.ts: -------------------------------------------------------------------------------- 1 | import { Expression, IMethodCallExpression, InstanceMethodCallExpression, NewExpression, StaticMethodCallExpression } from "../Ast/Expressions"; 2 | import { IMethodBase, IMethodBaseWithTrivia, MethodParameter } from "../Ast/Types"; 3 | import { AstTransformer } from "../AstTransformer"; 4 | 5 | export class UseDefaultCallArgsExplicitly extends AstTransformer { 6 | constructor() { super("UseDefaultCallArgsExplicitly"); } 7 | 8 | protected getNewArgs(args: Expression[], method: IMethodBaseWithTrivia): Expression[] { 9 | if ("UseDefaultCallArgsExplicitly" in method.attributes && method.attributes["UseDefaultCallArgsExplicitly"] === "disable") return args; 10 | if (args.length >= method.parameters.length) return args; 11 | 12 | const newArgs: Expression[] = []; 13 | for (let i = 0; i < method.parameters.length; i++) { 14 | const init = method.parameters[i].initializer; 15 | if (i >= args.length && init === null) { 16 | this.errorMan.throw(`Missing default value for parameter #${i + 1}!`); 17 | break; 18 | } 19 | newArgs.push(i < args.length ? args[i] : init); 20 | } 21 | return newArgs; 22 | } 23 | 24 | protected visitExpression(expr: Expression): Expression { 25 | super.visitExpression(expr); 26 | if (expr instanceof NewExpression && expr.cls.decl.constructor_ !== null) { 27 | expr.args = this.getNewArgs(expr.args, expr.cls.decl.constructor_); 28 | } else if (expr instanceof InstanceMethodCallExpression) 29 | expr.args = this.getNewArgs(expr.args, expr.method); 30 | else if (expr instanceof StaticMethodCallExpression) 31 | expr.args = this.getNewArgs(expr.args, expr.method); 32 | return expr; 33 | } 34 | } -------------------------------------------------------------------------------- /src/Parsers/Common/IParser.ts: -------------------------------------------------------------------------------- 1 | import { NodeManager } from "./NodeManager"; 2 | import { SourceFile } from "../../One/Ast/Types"; 3 | 4 | export interface IParser { 5 | parse(): SourceFile; 6 | nodeManager: NodeManager; 7 | } 8 | -------------------------------------------------------------------------------- /src/Parsers/Common/NodeManager.ts: -------------------------------------------------------------------------------- 1 | import { Reader } from "./Reader"; 2 | 3 | export class NodeManager { 4 | nodes: any[] = []; 5 | 6 | constructor(public reader: Reader) { 7 | } 8 | 9 | addNode(node: any, start: number): void { 10 | this.nodes.push(node); 11 | } 12 | } -------------------------------------------------------------------------------- /src/Parsers/Common/Utils.ts: -------------------------------------------------------------------------------- 1 | export class Utils { 2 | static getPadLen(line: string) { 3 | for (let i = 0; i < line.length; i++) 4 | if (line[i] !== ' ') 5 | return i; 6 | return -1; // whitespace line => pad === 0 7 | } 8 | 9 | static deindent(str: string): string { 10 | const lines = str.split(/\n/g); 11 | if (lines.length === 1) return str; 12 | 13 | if (this.getPadLen(lines[0]) === -1) 14 | lines.shift(); 15 | 16 | let minPadLen = 9999; 17 | for (const padLen of lines.map(x => this.getPadLen(x)).filter(x => x !== -1)) 18 | if (padLen < minPadLen) 19 | minPadLen = padLen; 20 | 21 | if (minPadLen === 9999) return lines.map(x => "").join("\n"); 22 | 23 | // @java final var minPadLen2 = minPadLen; 24 | const minPadLen2 = minPadLen; 25 | const newStr = lines.map(x => x.length >= minPadLen2 ? x.substr(minPadLen2) : x).join("\n"); 26 | return newStr; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/StdLib/PackageBundleSource.ts: -------------------------------------------------------------------------------- 1 | import { PackageSource, PackageId, PackageBundle } from "./PackageManager"; 2 | 3 | export class PackageBundleSource implements PackageSource { 4 | constructor(public bundle: PackageBundle) { } 5 | 6 | getPackageBundle(ids: PackageId[], cachedOnly: boolean): Promise { 7 | throw new Error("Method not implemented."); 8 | } 9 | 10 | async getAllCached(): Promise { 11 | return this.bundle; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/StdLib/PackagesFolderSource.ts: -------------------------------------------------------------------------------- 1 | // @python-import-all onelang_file 2 | // @php-use OneLang\File\OneFile 3 | import { OneFile } from "One.File-v0.1"; 4 | import { PackageSource, PackageId, PackageBundle, PackageContent, PackageType } from "./PackageManager"; 5 | 6 | export class PackagesFolderSource implements PackageSource { 7 | constructor(public packagesDir: string = "packages") { } 8 | 9 | getPackageBundle(ids: PackageId[], cachedOnly: boolean): Promise { 10 | throw new Error("Method not implemented."); 11 | } 12 | 13 | async getAllCached(): Promise { 14 | const packages: { [id: string]: PackageContent } = {}; 15 | const allFiles: string[] = OneFile.listFiles(this.packagesDir, true); 16 | for (let fn of allFiles) { 17 | const pathParts = fn.split(/\//g); // [0]=implementations/interfaces, [1]=package-name, [2:]=path 18 | if (pathParts.length < 3) continue; 19 | const type = pathParts.shift(); 20 | const pkgDir = pathParts.shift(); 21 | if (type !== "implementations" && type !== "interfaces") continue; // skip e.g. bundle.json 22 | const pkgIdStr = `${type}/${pkgDir}`; 23 | let pkg = packages[pkgIdStr]; 24 | if (!pkg) { 25 | const pkgDirParts: string[] = pkgDir.split(/-/g); 26 | const version = pkgDirParts.pop().replace(/^v/, ""); 27 | const pkgType = type === "implementations" ? PackageType.Implementation : PackageType.Interface; 28 | const pkgId = new PackageId(pkgType, pkgDirParts.join("-"), version); 29 | pkg = new PackageContent(pkgId, {}, true); 30 | packages[pkgIdStr] = pkg; 31 | } 32 | pkg.files[pathParts.join("/")] = OneFile.readText(`${this.packagesDir}/${fn}`); 33 | } 34 | return new PackageBundle(Object.values(packages)); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/Test/PackageStateCapture.ts: -------------------------------------------------------------------------------- 1 | import { Package } from "../One/Ast/Types"; 2 | import { TSOverviewGenerator } from "../Utils/TSOverviewGenerator"; 3 | 4 | export class PackageStateCapture { 5 | overviews: { [name: string]: string; } = {}; 6 | 7 | constructor(public pkg: Package) { 8 | for (const file of Object.values(pkg.files)) 9 | this.overviews[file.sourcePath.path] = new TSOverviewGenerator(false, false).generate(file); 10 | } 11 | 12 | getSummary() { 13 | return Object.keys(this.overviews).map(file => `=== ${file} ===\n\n${this.overviews[file]}`).join('\n\n'); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/Test/TestCase.ts: -------------------------------------------------------------------------------- 1 | export class TestCase { 2 | constructor(public name: string, public action: (artifactDir: string) => Promise) { } 3 | } 4 | 5 | export class SyncTestCase extends TestCase { 6 | constructor(name: string, public syncAction: (artifactDir: string) => void) { 7 | super(name, null); 8 | this.action = (artifactDir: string) => this.execute(artifactDir); 9 | } 10 | 11 | async execute(artifactDir: string): Promise { 12 | this.syncAction(artifactDir); 13 | } 14 | } 15 | 16 | export interface ITestCollection { 17 | name: string; 18 | getTestCases(): TestCase[]; 19 | } 20 | -------------------------------------------------------------------------------- /src/Test/TestCases/OneFileTests.ts: -------------------------------------------------------------------------------- 1 | // @php-use OneLang\File\OneFile 2 | // @python-import-all onelang_file 3 | import { OneFile } from "One.File-v0.1"; 4 | 5 | import { ITestCollection, SyncTestCase, TestCase } from "../TestCase"; 6 | 7 | export class OneFileTests implements ITestCollection { 8 | name = "OneFileTests"; 9 | 10 | constructor(public baseDir: string) { } 11 | 12 | listXCompiledNativeSources() { 13 | console.log(OneFile.listFiles(`${this.baseDir}/xcompiled-src/native`, true).join("\n")); 14 | } 15 | 16 | getTestCases(): TestCase[] { 17 | return [ 18 | new SyncTestCase("ListXCompiledNativeSources", _ => this.listXCompiledNativeSources()) 19 | ]; 20 | } 21 | } -------------------------------------------------------------------------------- /src/Test/TestCases/ProjectGeneratorTest.ts: -------------------------------------------------------------------------------- 1 | // @python-import-all onelang_file 2 | // @php-use OneLang\File\OneFile 3 | import { OneFile } from "One.File-v0.1"; 4 | 5 | import { ITestCollection, TestCase } from "../TestCase"; 6 | import { CompilerHelper } from "../../One/CompilerHelper"; 7 | import { Compiler, ICompilerHooks } from "../../One/Compiler"; 8 | import { PackageStateCapture } from "../PackageStateCapture"; 9 | import { ProjectGenerator } from "../../Generator/ProjectGenerator"; 10 | 11 | export class StageExporter implements ICompilerHooks { 12 | stage = 0; 13 | 14 | constructor(public artifactDir: string, public compiler: Compiler) { } 15 | 16 | afterStage(stageName: string): void { 17 | console.log(`Stage finished: ${stageName}`); 18 | OneFile.writeText(`${this.artifactDir}/stages/${this.stage}_${stageName}.txt`, new PackageStateCapture(this.compiler.projectPkg).getSummary()); 19 | this.stage++; 20 | } 21 | } 22 | 23 | export class ProjectGeneratorTest implements ITestCollection { 24 | name: string = "ProjectGeneratorTest"; 25 | 26 | constructor(public baseDir: string) { } 27 | 28 | getTestCases(): TestCase[] { 29 | return [new TestCase("OneLang", artifactDir => this.compileOneLang(artifactDir))]; 30 | } 31 | 32 | async compileOneLang(artifactDir: string): Promise { 33 | console.log("Initalizing project generator..."); 34 | const projGen = new ProjectGenerator(this.baseDir, `${this.baseDir}/xcompiled-src`); 35 | projGen.outDir = `${artifactDir}/output/`; 36 | 37 | console.log("Initalizing project for compiler..."); 38 | const compiler = await CompilerHelper.initProject(projGen.projectFile.name, projGen.srcDir, projGen.projectFile.sourceLang, null); 39 | compiler.hooks = new StageExporter(artifactDir, compiler); 40 | 41 | console.log("Processing workspace..."); 42 | compiler.processWorkspace(); 43 | 44 | console.log("Generating project..."); 45 | await projGen.generate(); 46 | } 47 | } -------------------------------------------------------------------------------- /src/Utils/ArrayHelper.ts: -------------------------------------------------------------------------------- 1 | export class ArrayHelper { 2 | static sortBy(items: T[], keySelector: (item: T) => number): T[] { 3 | // @java-import java.util.Arrays 4 | // @java Arrays.sort(items, (a, b) -> keySelector.apply(a) - keySelector.apply(b)); 5 | // @java return items; 6 | // @php return sort(items); 7 | return items.sort((a: T, b: T) => keySelector(a) - keySelector(b)); 8 | } 9 | 10 | static removeLastN(items: T[], count: number): void { 11 | // @java items.subList(items.size() - count, items.size()).clear(); 12 | items.splice(items.length - count, count); 13 | } 14 | } -------------------------------------------------------------------------------- /src/Utils/StatementDebugger.ts: -------------------------------------------------------------------------------- 1 | import { AstTransformer } from "../One/AstTransformer"; 2 | import { Statement } from "../One/Ast/Statements"; 3 | import { TSOverviewGenerator } from "./TSOverviewGenerator"; 4 | import { Expression } from "../One/Ast/Expressions"; 5 | import { Field } from "../One/Ast/Types"; 6 | 7 | export class StatementDebugger extends AstTransformer { 8 | constructor(public stmtFilterRegex: string) { super("StatementDebugger"); } 9 | 10 | protected visitExpression(expr: Expression): Expression { 11 | // optimization: no need to process these... 12 | return null; 13 | } 14 | 15 | protected visitField(field: Field): void { 16 | //if (field.name === "type" && field.parentInterface.name === "Interface") debugger; 17 | super.visitField(field); 18 | } 19 | 20 | protected visitStatement(stmt: Statement): Statement { 21 | const stmtRepr = TSOverviewGenerator.preview.stmt(stmt); 22 | // if (new RegExp(this.stmtFilterRegex).test(stmtRepr)) 23 | // debugger; 24 | return super.visitStatement(stmt); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/VM/Values.ts: -------------------------------------------------------------------------------- 1 | export interface IVMValue { 2 | equals(other: IVMValue): boolean; 3 | } 4 | 5 | export interface ICallableValue extends IVMValue { 6 | call(args: IVMValue[]): IVMValue; 7 | } 8 | 9 | export class ObjectValue implements IVMValue { 10 | constructor(public props: { [name: string]: IVMValue }) { } 11 | equals(other: IVMValue): boolean { return false; } 12 | } 13 | 14 | export class StringValue implements IVMValue { 15 | constructor(public value: string) { } 16 | 17 | equals(other: IVMValue): boolean { 18 | return other instanceof StringValue && other.value === this.value; 19 | } 20 | } 21 | 22 | export class NumericValue implements IVMValue { 23 | constructor(public value: number) { } 24 | 25 | equals(other: IVMValue): boolean { 26 | return other instanceof NumericValue && other.value === this.value; 27 | } 28 | } 29 | 30 | export class BooleanValue implements IVMValue { 31 | constructor(public value: boolean) { } 32 | 33 | equals(other: IVMValue): boolean { 34 | return other instanceof BooleanValue && other.value === this.value; 35 | } 36 | } 37 | 38 | export class ArrayValue implements IVMValue { 39 | constructor(public items: IVMValue[]) { } 40 | equals(other: IVMValue): boolean { return false; } 41 | } -------------------------------------------------------------------------------- /test/src/ExpressionTest.ts: -------------------------------------------------------------------------------- 1 | import 'module-alias/register'; 2 | import { TypeScriptParser2 } from "@one/Parsers/TypeScriptParser"; 3 | 4 | function exprToJson(exprStr: string) { 5 | const expr = new TypeScriptParser2(exprStr).parseExpression(); 6 | const json = JSON.stringify(expr, (k, v) => { 7 | if (v === null) return undefined; 8 | if (Array.isArray(v) || typeof v !== "object") return v; 9 | 10 | const res = {}; 11 | res["$type"] = v.constructor.name; 12 | for (const key of Object.keys(v)) 13 | res[key] = v[key]; 14 | return res; 15 | }, 4); 16 | return json; 17 | } 18 | 19 | console.log(exprToJson("`\\``")); 20 | 21 | -------------------------------------------------------------------------------- /test/src/SelfTest.ts: -------------------------------------------------------------------------------- 1 | import 'module-alias/register'; 2 | import 'process'; 3 | 4 | process.env.NODE_PATH = `${__dirname}/../../onepkg`; 5 | require("module").Module._initPaths(); 6 | 7 | import { TestRunner } from "@one/Test/TestRunner"; 8 | 9 | new TestRunner(`${__dirname}/../../`, process.argv).runTests(); -------------------------------------------------------------------------------- /test/src/UtilityTest.ts: -------------------------------------------------------------------------------- 1 | import { TypeScriptParser2 } from "@one/Parsers/TypeScriptParser"; 2 | import * as assert from "assert"; 3 | 4 | function it2(fn: Mocha.Func) { 5 | it(fn.toString(), fn); 6 | } 7 | 8 | describe("TypeScriptParser2.calculateRelativePath", () => { 9 | function test(currFile: string, relPath: string, result: string|"throws") { 10 | if(result === "throws") 11 | it(`calculateRelativePath("${currFile}", "${relPath}") throws`, 12 | () => assert.throws(() => TypeScriptParser2.calculateRelativePath(currFile, relPath))); 13 | else 14 | it(`calculateRelativePath("${currFile}", "${relPath}") === "${result}"`, 15 | () => assert.equal(TypeScriptParser2.calculateRelativePath(currFile, relPath), result)); 16 | } 17 | 18 | test("a", "b", "throws"); 19 | test("a", "./b", "b"); 20 | test("a", ".//b", "throws"); 21 | test("a/b", "./c", "a/c"); 22 | test("a/b", "../c", "c"); 23 | test("a/b/c", "../d", "a/d"); 24 | test("a/b/c", "../../d", "d"); 25 | test("a/b/c", "../../../d", "throws"); 26 | }); -------------------------------------------------------------------------------- /test/src/Utils/Underscore.ts: -------------------------------------------------------------------------------- 1 | export class Linq { 2 | constructor(public items: T[]) { } 3 | 4 | except(items: T[]) { return new Linq(this.items.filter(item => !items.includes(item))); } 5 | intersect(items: T[]) { return new Linq(this.items.filter(item => items.includes(item))); } 6 | 7 | selectMany(selector: (item: T) => T2[]): Linq { 8 | return new Linq(this.items.reduce((acc, val) => acc.concat(new Linq(selector(val)).get()), [])); 9 | } 10 | 11 | map(selector: (item: T, i: number) => T2) { return new Linq(this.items.map(selector)); } 12 | //flat() { return new Linq(this.items.flat()); } 13 | take(count: number): Linq { return new Linq(this.items.filter((_, i) => i < count)); } 14 | skip(count: number): Linq { return new Linq(this.items.filter((_, i) => i >= count)); } 15 | join(separator: string) { return this.items.join(separator); } 16 | concat(arr2: T[]) { return new Linq(this.items.concat(arr2)); } 17 | 18 | toObject(keySelector: (item: T) => string) { 19 | const result: { [key: string]: T } = { }; 20 | for (const item of this.items) 21 | result[keySelector(item)] = item; 22 | return result; 23 | } 24 | 25 | toMap(keySelector: (item: T) => string) { 26 | const result = new Map(); 27 | for (const item of this.items) 28 | result.set(keySelector(item), item); 29 | return result; 30 | } 31 | 32 | get(): T[] { return this.items; } 33 | last(): T { return this.items[this.items.length - 1]; } 34 | } 35 | -------------------------------------------------------------------------------- /test/src/testSuites/ParserTest.ts: -------------------------------------------------------------------------------- 1 | import { glob, readFile } from '../Utils/TestUtils'; 2 | import { TypeScriptParser2 } from "@one/Parsers/TypeScriptParser"; 3 | 4 | function testFolder(folder: string) { 5 | const files = glob(folder).filter(x => x.endsWith(".ts")); 6 | for (const file of files) 7 | it(file, () => TypeScriptParser2.parseFile(readFile(`${folder}/${file}`))); 8 | } 9 | 10 | describe("Native resolvers", () => testFolder("langs/NativeResolvers")); 11 | describe("Package interfaces", () => testFolder("packages/interfaces")); 12 | describe("Test inputs", () => testFolder("test/testSuites/CompilationTest")); -------------------------------------------------------------------------------- /test/test.js: -------------------------------------------------------------------------------- 1 | describe('Expression language (ExprLang)', function () { 2 | describe('Tokenizer (Lexer) tests', () => require("./lib/testSuites/ExprLang-LexerTest")); 3 | describe('Parser tests', () => require("./lib/testSuites/ExprLang-ParserTest")); 4 | describe('Parser AST tests', () => require("./lib/testSuites/ExprLang-ParserAstTest")); 5 | describe('VM tests', () => require("./lib/testSuites/ExprLang-VMTest")); 6 | }); 7 | 8 | describe('OneTemplate', () => require("./lib/testSuites/OneTemplateTest")); 9 | //describe('OneLang Parser tests', () => require("./lib/testSuites/ParserTest")); 10 | //describe("Compilation tests", () => require("./lib/testSuites/CompilationTest")); 11 | -------------------------------------------------------------------------------- /test/testSuites/CompilationTest/ArrayTest.ts: -------------------------------------------------------------------------------- 1 | class TestClass { 2 | testMethod() { 3 | let constantArr = [5]; 4 | 5 | let mutableArr = [1]; 6 | mutableArr.push(2); 7 | 8 | console.log(`len1: ${constantArr.length}, len2: ${mutableArr.length}`); 9 | } 10 | } -------------------------------------------------------------------------------- /test/testSuites/CompilationTest/BigInteger.ts: -------------------------------------------------------------------------------- 1 | class MathUtils { 2 | static calc(n: number): number { 3 | let result = 1; 4 | for (let i = 2; i <= n; i++) { 5 | result = result * i; 6 | if (result > 10) 7 | result = result >> 2; 8 | } 9 | return result; 10 | } 11 | 12 | static calcBig(n: number): OneBigInteger { 13 | let result = OneBigInteger.fromInt(1); 14 | for (let i = 2; i <= n; i++) { 15 | result = result * i + 123; 16 | result = result + result; 17 | if (result > 10) 18 | result = result >> 2; 19 | } 20 | return result; 21 | } 22 | } 23 | 24 | console.log(`5 -> ${MathUtils.calc(5)}, 24 -> ${MathUtils.calcBig(24)}`); 25 | -------------------------------------------------------------------------------- /test/testSuites/CompilationTest/BooleanTest.ts: -------------------------------------------------------------------------------- 1 | class TestClass { 2 | testMethod() { 3 | var a = true; 4 | var b = false; 5 | var c = a && b; 6 | var d = a || b; 7 | console.log(`a: ${a}, b: ${b}, c: ${c}, d: ${d}`); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /test/testSuites/CompilationTest/CharacterTest.ts: -------------------------------------------------------------------------------- 1 | class TestClass { 2 | testMethod() { 3 | const str = "a1A"; 4 | for (var i = 0; i < str.length; i++) { 5 | const c = str[i]; 6 | const isUpper = "A" <= c && c <= "Z"; 7 | const isLower = "a" <= c && c <= "z"; 8 | const isNumber = "0" <= c && c <= "9"; 9 | console.log(isUpper ? "upper" : isLower ? "lower" : isNumber ? "number" : "other"); 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /test/testSuites/CompilationTest/ConstrInferBug.ts: -------------------------------------------------------------------------------- 1 | class TestClass { 2 | methodTest(methodParam: string[]) { } 3 | testMethod() { } 4 | } 5 | -------------------------------------------------------------------------------- /test/testSuites/CompilationTest/ConstructorTest.ts: -------------------------------------------------------------------------------- 1 | class ConstructorTest { 2 | field2: number; 3 | 4 | constructor(public field1: number) { 5 | this.field2 = field1 * this.field1 * 5; 6 | } 7 | } 8 | 9 | class TestClass { 10 | testMethod() { 11 | const test = new ConstructorTest(3); 12 | console.log(test.field2); // 45 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /test/testSuites/CompilationTest/EnumAsFieldTest.ts: -------------------------------------------------------------------------------- 1 | enum SomeKind { EnumVal0, EnumVal1, EnumVal2 } 2 | 3 | class TestClass { 4 | enumField: SomeKind = SomeKind.EnumVal2; 5 | 6 | testMethod() { 7 | console.log(`Value: ${this.enumField}`); 8 | } 9 | } -------------------------------------------------------------------------------- /test/testSuites/CompilationTest/EnumTest.ts: -------------------------------------------------------------------------------- 1 | enum TestEnum { Item1, Item2 } 2 | 3 | class TestClass { 4 | testMethod() { 5 | let enumV = TestEnum.Item1; 6 | if (3 * 2 === 6) 7 | enumV = TestEnum.Item2; 8 | 9 | const check1 = enumV === TestEnum.Item2 ? "SUCCESS" : "FAIL"; 10 | const check2 = enumV === TestEnum.Item1 ? "FAIL" : "SUCCESS"; 11 | 12 | console.log(`Item1: ${TestEnum.Item1}, Item2: ${enumV}, checks: ${check1} ${check2}`); 13 | } 14 | } -------------------------------------------------------------------------------- /test/testSuites/CompilationTest/ExceptionTest.ts: -------------------------------------------------------------------------------- 1 | class TestClass { 2 | notThrows(): number { return 5; } 3 | fThrows() { OneError.raise("exception message"); } 4 | testMethod() { 5 | console.log(this.notThrows()); 6 | this.fThrows(); 7 | //OneError.raise("exception message"); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /test/testSuites/CompilationTest/ExplicitGenericTypeTest.ts: -------------------------------------------------------------------------------- 1 | class TestClass { 2 | testMethod() { 3 | const result: string[] = ["y"]; 4 | const map = { x:5 }; 5 | const keys = Object.keys(map); 6 | console.log(result[0]); 7 | console.log(keys[0]); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /test/testSuites/CompilationTest/ExplicitTypeTest.ts: -------------------------------------------------------------------------------- 1 | class TestClass { 2 | testMethod() { 3 | let op: string = "x"; 4 | console.log(op.length); 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /test/testSuites/CompilationTest/FakeEnumTest.ts: -------------------------------------------------------------------------------- 1 | class TokenType { 2 | static EndToken: string = "EndToken"; 3 | static Whitespace: string = "Whitespace"; 4 | static Identifier: string = "Identifier"; 5 | static OperatorX: string = "Operator"; 6 | static NoInitializer: string; 7 | } 8 | 9 | const casingTest = TokenType.EndToken; 10 | console.log(casingTest); 11 | -------------------------------------------------------------------------------- /test/testSuites/CompilationTest/FileTest.ts: -------------------------------------------------------------------------------- 1 | OneFile.writeText("test.txt", "example content"); 2 | const fileContent = OneFile.readText("test.txt"); 3 | console.log(fileContent); 4 | -------------------------------------------------------------------------------- /test/testSuites/CompilationTest/GenericsTest.ts: -------------------------------------------------------------------------------- 1 | class MapX { 2 | value: V; 3 | set(key: K, value: V) { this.value = value; } 4 | get(key: K): V { return this.value; } 5 | } 6 | 7 | class TestClass { 8 | testMethod() { 9 | const mapX = new MapX(); 10 | mapX.set("hello", 3); 11 | const numValue = mapX.get("hello2"); 12 | console.log(`${numValue}`); 13 | } 14 | } -------------------------------------------------------------------------------- /test/testSuites/CompilationTest/HelloWorld.ts: -------------------------------------------------------------------------------- 1 | class TestClass { 2 | testMethod() { 3 | const value = 1 + 2 * 3 - 4; 4 | const map_ = { a:5, b:6 }; 5 | const text = `Hello world! value = ${value}, map[a] = ${map_["a"]}`; 6 | console.log(text); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /test/testSuites/CompilationTest/HelloWorldRaw.ts: -------------------------------------------------------------------------------- 1 | console.log("Hello world!"); -------------------------------------------------------------------------------- /test/testSuites/CompilationTest/InheritanceTest.ts: -------------------------------------------------------------------------------- 1 | interface IPrinterBase { 2 | someBaseFunc(): number; 3 | } 4 | 5 | interface IPrinter extends IPrinterBase { 6 | printIt(): void; 7 | } 8 | 9 | class BasePrinter implements IPrinter { 10 | numValue = 42; 11 | 12 | // @virtual 13 | getValue(): string { return "Base"; } 14 | 15 | printIt() { 16 | console.log(`BasePrinter: ${this.getValue()}`); 17 | } 18 | 19 | someBaseFunc(): number { return this.numValue; } 20 | } 21 | 22 | class ChildPrinter extends BasePrinter { 23 | // @override 24 | getValue(): string { return "Child"; } 25 | } 26 | 27 | class TestClass { 28 | getPrinter(name: string): IPrinter { 29 | const result: IPrinter = name === "child" ? new ChildPrinter() : new BasePrinter(); 30 | return result; 31 | } 32 | 33 | testMethod() { 34 | const basePrinter = this.getPrinter("base"); 35 | const childPrinter = this.getPrinter("child"); 36 | basePrinter.printIt(); 37 | childPrinter.printIt(); 38 | console.log(`${basePrinter.someBaseFunc()} == ${childPrinter.someBaseFunc()}`); 39 | 40 | var baseP2 = new BasePrinter(); 41 | var childP2 = new ChildPrinter(); 42 | console.log(`${baseP2.numValue} == ${childP2.numValue}`); 43 | } 44 | } -------------------------------------------------------------------------------- /test/testSuites/CompilationTest/JsonParseTest.ts: -------------------------------------------------------------------------------- 1 | const obj1 = OneJson.parse('{ "a":1, "b":2 }'); 2 | if(!obj1.isObject()) OneError.raise("expected to be object!"); 3 | const obj1Props = obj1.asObject().getProperties(); 4 | if (obj1Props.length !== 2) OneError.raise("expected 2 properties"); 5 | if (obj1Props[0].getName() !== "a") OneError.raise("expected first property to be named 'a'"); 6 | const obj1Prop0Value = obj1Props[0].getValue(obj1); 7 | if (!obj1Prop0Value.isNumber() || obj1Prop0Value.asNumber() !== 1) OneError.raise("expected 'a' to be 1 (number)"); 8 | console.log(`b = ${obj1.asObject().get("b").asNumber()}`); -------------------------------------------------------------------------------- /test/testSuites/CompilationTest/MapKeyTest.ts: -------------------------------------------------------------------------------- 1 | class TestClass { 2 | testMethod() { 3 | const map = {}; 4 | const keys = Object.keys(map); 5 | } 6 | } -------------------------------------------------------------------------------- /test/testSuites/CompilationTest/MapTest.ts: -------------------------------------------------------------------------------- 1 | class TestClass { 2 | getResult(): number { 3 | let mapObj = { x: 5 }; 4 | //let containsX = "x" in mapObj; 5 | //delete mapObj["x"]; 6 | mapObj["x"] = 3; 7 | return mapObj["x"]; 8 | //const xVal = mapObj["x"]; 9 | //return containsX 10 | } 11 | 12 | testMethod() { 13 | console.log(`Result = ${this.getResult()}`); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /test/testSuites/CompilationTest/MultiLangTest.ts: -------------------------------------------------------------------------------- 1 | class Calculator { 2 | factor(n: number) { 3 | if (n <= 1) { 4 | return 1; 5 | } else { 6 | return this.factor(n - 1) * n; 7 | } 8 | } 9 | } 10 | 11 | console.log("Hello!"); 12 | 13 | const arr = [1, 2, 3]; 14 | arr.push(4); 15 | 16 | console.log(`n = ${arr.length}, arr[0] = ${arr[0]}`); 17 | 18 | const map = { 19 | a: 2, 20 | b: 3 21 | }; 22 | console.log(`map['a'] = ${map["a"]}, arr[1] = ${arr[1]}`); 23 | 24 | if (arr[0] == 1) { 25 | console.log("TRUE-X"); 26 | } else { 27 | console.log("FALSE"); 28 | } 29 | 30 | let sum = 0; 31 | for (let i = 0; i < 10; i++) { 32 | sum += i + 2; 33 | } 34 | console.log(sum); 35 | 36 | const calc = new Calculator(); 37 | console.log(`5! = ${calc.factor(5)}`); 38 | -------------------------------------------------------------------------------- /test/testSuites/CompilationTest/NumberUnaryIssue.ts: -------------------------------------------------------------------------------- 1 | class NumberUnaryIssue { 2 | test(num: number) { 3 | num--; 4 | } 5 | } 6 | 7 | console.log("ok"); -------------------------------------------------------------------------------- /test/testSuites/CompilationTest/StdoutTest.ts: -------------------------------------------------------------------------------- 1 | class TestClass { 2 | reverseString(str: string): string { 3 | let result = ""; 4 | for (let i = str.length - 1; i >= 0; i--) 5 | result += str[i]; 6 | return result; 7 | } 8 | 9 | /*reverseString2(str: string): string { 10 | let result = ""; 11 | for (const c of str) 12 | result += c; 13 | return result; 14 | }*/ 15 | 16 | testMethod(): string { 17 | console.log(this.reverseString("print value")); 18 | return "return value"; 19 | } 20 | } -------------------------------------------------------------------------------- /test/testSuites/CompilationTest/StrLenInferIssue.ts: -------------------------------------------------------------------------------- 1 | class StrLenInferIssue { 2 | static test(str: string): number { 3 | return str.length; 4 | } 5 | } 6 | 7 | console.log(StrLenInferIssue.test("hello")); -------------------------------------------------------------------------------- /test/testSuites/CompilationTest/StrReplaceTest.ts: -------------------------------------------------------------------------------- 1 | class TestClass { 2 | testMethod() { 3 | const str = "A x B x C x D"; 4 | const result = str.replace("x", "y"); 5 | console.log(`R: ${result}, O: ${str}`); 6 | } 7 | } -------------------------------------------------------------------------------- /test/testSuites/CompilationTest/StringTest.ts: -------------------------------------------------------------------------------- 1 | class TestClass { 2 | testMethod(): string { 3 | var x = "x"; 4 | var y = "y"; 5 | 6 | var z = "z"; 7 | z += "Z"; 8 | z += x; 9 | 10 | var a = "abcdef".substring(2,4); 11 | var arr = "ab cd ef".split(" "); 12 | 13 | return z + "|" + x + y + "|" + a + "|" + arr[2]; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /test/testSuites/CompilationTest/StructureTest1.ts: -------------------------------------------------------------------------------- 1 | class MyList { 2 | items: T[]; 3 | } 4 | 5 | class Item { 6 | offset: number = 5; 7 | strTest: string = 'test' + 'test2'; 8 | constructor(public strConstr: string = "constr") { } 9 | } 10 | 11 | class Container { 12 | itemList: MyList; 13 | stringList: MyList; 14 | 15 | method0(){} 16 | method1(str: string = "x"){ return str; } 17 | } 18 | 19 | console.log("ok"); -------------------------------------------------------------------------------- /test/testSuites/CompilationTest/SubstrMatchTest.ts: -------------------------------------------------------------------------------- 1 | class TestClass { 2 | testMethod() { 3 | const str = "ABCDEF"; 4 | const tA0_true = str.startsWith("A", 0); 5 | const tA1_false = str.startsWith("A", 1); 6 | const tB1_true = str.startsWith("B", 1); 7 | const tCD2_true = str.startsWith("CD", 2); 8 | console.log(`${tA0_true} ${tA1_false} ${tB1_true} ${tCD2_true}`); 9 | } 10 | } -------------------------------------------------------------------------------- /test/testSuites/CompilationTest/TemplateString.ts: -------------------------------------------------------------------------------- 1 | class TestClass { 2 | testMethod() { 3 | const strVal = "str"; 4 | const num = 1337; 5 | const b = true; 6 | const result = `before ${strVal}, num: ${num}, true: ${b} after`; 7 | console.log(result); 8 | console.log(`before ${strVal}, num: ${num}, true: ${b} after`); 9 | 10 | const result2 = "before " + strVal + ", num: " + num + ", true: " + b + " after"; 11 | console.log(result2); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /test/testSuites/CompilationTest/TernaryTest.ts: -------------------------------------------------------------------------------- 1 | class TestClass { 2 | getResult(): boolean { return true; } 3 | 4 | testMethod() { 5 | console.log(this.getResult() ? "true" : "false"); 6 | } 7 | } -------------------------------------------------------------------------------- /test/testSuites/ExprLang-Lexer.yaml: -------------------------------------------------------------------------------- 1 | '2+3': [{n: "2"}, {op: +}, {n: "3"}] 2 | 'not true': [{op: "not"}, {i: "true"}] 3 | '!true': [{op: "!"}, {i: "true"}] 4 | 'f(1,2)': [{i: "f"}, {op: "("}, {n: "1"}, {op: ","}, {n: "2"}, {op: ")"}] 5 | 'not o.a and o.b or o.c': [ 6 | {op: "not"}, {i: "o"}, {op: "."}, {i: "a"}, 7 | {op: "and"}, {i: "o"}, {op: "."}, {i: "b"}, 8 | {op: "or"}, {i: "o"}, {op: "."}, {i: "c"}] 9 | 'a || b && c': [{i: "a"}, {op: "||"}, {i: "b"}, {op: "&&"}, {i: "c"}] 10 | '-3': [{n: "-3"}] 11 | '.123': [{n: ".123"}] 12 | '123.456': [{n: "123.456"}] 13 | '0x1a2b': [{n: "0x1a2b"}] 14 | '0b0101': [{n: "0b0101"}] 15 | '-a': [{op: "-"}, {i: "a"}] 16 | '- 5': [{op: "-"}, {n: "5"}] 17 | '+ -5': [{op: "+"}, {n: "-5"}] 18 | 'a + -5': [{i: "a"}, {op: "+"}, {n: "-5"}] 19 | 'a + + -5': [{i: "a"}, {op: "+"}, {op: "+"}, {n: "-5"}] 20 | '0b01z': {errorOffset: 4, message: "invalid character in number"} 21 | '0b01 z': {errorOffset: 5, message: "expected operator here"} 22 | '0x01 + z': [{n: "0x01"}, {op: "+"}, {i: "z"}] 23 | '- -0x01 + z': [{op: "-"}, {n: "-0x01"}, {op: "+"}, {i: "z"}] 24 | '/': [{op: "/"}] 25 | '"alma"': [{s: "alma"}] 26 | "'alma'": [{s: "alma"}] 27 | "'a'+'b'": [{s: "a"}, {op: "+"}, {s: "b"}] 28 | "'A\\'B'": [{s: "A'B"}] 29 | 'a == 0 && b == null': [ 30 | {i: "a"}, {op: "=="}, {n: "0"}, 31 | {op: "&&"}, 32 | {i: "b"}, {op: "=="}, {i: "null"}] -------------------------------------------------------------------------------- /test/testSuites/ExprLang-Parser.yaml: -------------------------------------------------------------------------------- 1 | 'a': 'a' 2 | '1': '1' 3 | '"x"': '"x"' 4 | '!condition': '!condition' 5 | '~-condition': '~(-condition)' 6 | '2+3': '2 + 3' 7 | '1-2-3': '(1 - 2) - 3' 8 | '1-(2-3)': '1 - (2 - 3)' 9 | 'a ? 1 : 2': 'a ? 1 : 2' 10 | 'f()': 'f()' 11 | 'f(1)': 'f(1)' 12 | 'f(1,2)': 'f(1, 2)' 13 | 'obj.method': 'obj.method' 14 | 'obj.subObj.method': '(obj.subObj).method' 15 | 'obj.method(1 + 3 * 6, "alma")': '(obj.method)((1 + (3 * 6)), "alma")' 16 | 'obj[x]': 'obj[x]' 17 | 'obj[x + y]': 'obj[(x + y)]' 18 | 'obj[x](a)[z]': '((obj[x])(a))[z]' 19 | 'a && b': 'a && b' 20 | 'a == 0 && b == null': '(a == 0) && (b == null)' 21 | 'a && b || c': '(a && b) || c' 22 | 'a + b * c ** d == 5 - 1 && x <= y ? 9 : 8': '(((a + (b * (c ** d))) == (5 - 1)) && (x <= y)) ? 9 : 8' 23 | 'not a and b': '(!a) && b' 24 | "not expr.expression.valueType.isVoid and expr.expression.exprKind == 'Call'": '(!(((expr.expression).valueType).isVoid)) && (((expr.expression).exprKind) == "Call")' -------------------------------------------------------------------------------- /test/testSuites/ExprLang-ParserAst.yaml: -------------------------------------------------------------------------------- 1 | 'a': { text: a } 2 | '1': { type: 0, value: 1 } 3 | '"x"': { type: 1, value: x } 4 | '!condition': 5 | op: "!" 6 | expr: { text: condition } 7 | '~-condition': 8 | op: "~" 9 | expr: 10 | op: "-" 11 | expr: { text: condition } 12 | '2+3': 13 | op: + 14 | left: { type: 0, value: 2 } 15 | right: { type: 0, value: 3 } 16 | '1-2-3': 17 | op: "-" 18 | left: 19 | op: "-" 20 | left: { type: 0, value: 1 } 21 | right: { type: 0, value: 2 } 22 | right: { type: 0, value: 3 } -------------------------------------------------------------------------------- /test/testSuites/ExprLang-VM.yaml: -------------------------------------------------------------------------------- 1 | '1': { expected: 1 } 2 | 'a': { expected: 2, model: { a: 2 } } 3 | '"a"': { expected: "a" } 4 | '1+2': { expected: 3 } 5 | '1-2-3': { expected: -4 } 6 | 'obj.method(9)': { expected: 20 } 7 | 'obj.a + obj.b / 2 + c': { expected: 10, model: { c: 2 } } -------------------------------------------------------------------------------- /test/testSuites/ProjectTest/ComplexTest01/src/ComplexTest01.ts: -------------------------------------------------------------------------------- 1 | import { GroupManager } from "./Model/GroupManager"; 2 | import { StringUtil } from "./Utils/StringUtil"; 3 | import { Group } from "./Model/Db/Group"; 4 | import { ArrayUtil } from "./Utils/ArrayUtil"; 5 | 6 | const gm = new GroupManager(); 7 | gm.generateANewGroup(); 8 | gm.importGroup('{"name":"importedGroup", "users":[{"name":"imported user1"}]}'); 9 | const groups = gm.groups.get(); 10 | const newGroup = new Group(); 11 | newGroup.name = "NewGroup"; 12 | const allGroups = ArrayUtil.concat(groups, [newGroup]); 13 | const groupNames = StringUtil.concatTwoStrings(groups[0].name, allGroups[2].name); 14 | console.log(`Group names: ${groupNames}`); -------------------------------------------------------------------------------- /test/testSuites/ProjectTest/ComplexTest01/src/Model/Db/Group.ts: -------------------------------------------------------------------------------- 1 | import { User } from "./User"; 2 | import { List } from "../../Utils/List"; 3 | 4 | export class Group { 5 | public name: string; 6 | public users: User[]; 7 | } -------------------------------------------------------------------------------- /test/testSuites/ProjectTest/ComplexTest01/src/Model/Db/User.ts: -------------------------------------------------------------------------------- 1 | export class User { 2 | constructor(public name: string) { } 3 | } -------------------------------------------------------------------------------- /test/testSuites/ProjectTest/ComplexTest01/src/Model/GroupManager.ts: -------------------------------------------------------------------------------- 1 | import { OneJson } from "One.Json-v0.1"; 2 | 3 | import { Group } from "./Db/Group"; 4 | import { User } from "./Db/User"; 5 | import { StringUtil } from "../Utils/StringUtil"; 6 | import { List } from "../Utils/List"; 7 | 8 | export class GroupManager { 9 | public groups = new List(); 10 | 11 | generateANewGroup(): void { 12 | const g = new Group(); 13 | g.name = "MyGroup"; 14 | g.users = [new User("user1"), new User("user2")]; 15 | this.groups.add(g); 16 | } 17 | 18 | importGroup(exportedJson: string): void { 19 | const g = OneJson.deserialize(exportedJson); 20 | g.name = StringUtil.ucFirst(g.name); 21 | this.groups.add(g); 22 | } 23 | } -------------------------------------------------------------------------------- /test/testSuites/ProjectTest/ComplexTest01/src/Utils/ArrayUtil.ts: -------------------------------------------------------------------------------- 1 | export class ArrayUtil { 2 | static concat(arr1: T[], arr2: T[]): T[] { 3 | const result: T[] = []; 4 | for (const item of arr1) 5 | result.push(item); 6 | for (const item of arr2) 7 | result.push(item); 8 | return result; 9 | } 10 | } -------------------------------------------------------------------------------- /test/testSuites/ProjectTest/ComplexTest01/src/Utils/List.ts: -------------------------------------------------------------------------------- 1 | export class List { 2 | items: T[]; 3 | 4 | add(item: T): void { 5 | this.items.push(item); 6 | } 7 | 8 | get(): T[] { return this.items; } 9 | } -------------------------------------------------------------------------------- /test/testSuites/ProjectTest/ComplexTest01/src/Utils/StringUtil.ts: -------------------------------------------------------------------------------- 1 | export class StringUtil { 2 | static ucFirst(str: string): string { return str[0].toUpperCase() + str.substr(1); } 3 | // hello 4 | // @attribute text 5 | static concatTwoStrings(str1: string, str2: string): string { return str1 + ", " + str2; } 6 | } -------------------------------------------------------------------------------- /test/testSuites/ProjectTest/ComplexTest01/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "baseUrl": "./", 4 | "target": "es2017", 5 | "module": "CommonJS", 6 | "outDir": "dist", 7 | "moduleResolution": "node", 8 | "paths": { "*": ["../../../../packages/interfaces/*"]} 9 | }, 10 | "include": ["src/**/*.ts"], 11 | } -------------------------------------------------------------------------------- /test/testSuites/ProjectTest/ImportTest/src/ImportTest.ts: -------------------------------------------------------------------------------- 1 | import { OneJson } from "One.Json-v0.1"; 2 | 3 | const value = OneJson.parse("5"); 4 | console.log(`isNumber: ${value.isNumber}`); -------------------------------------------------------------------------------- /test/testSuites/ProjectTest/ImportTest/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "baseUrl": "./", 4 | "target": "es2017", 5 | "outDir": "dist", 6 | "moduleResolution": "node", 7 | "paths": { "*": ["../../../../packages/interfaces/*" ]} 8 | }, 9 | "include": ["src/**/*.ts"], 10 | } -------------------------------------------------------------------------------- /test/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "baseUrl": "../", 4 | "paths": { 5 | "@one/*": ["src/*"], 6 | "*": ["onepkg/*"] 7 | }, 8 | "target": "es2020", 9 | "module": "umd", 10 | "moduleResolution": "node", 11 | "sourceMap": true, 12 | "outDir": "lib", 13 | "experimentalDecorators": true, 14 | "lib": ["es2020.string"] 15 | }, 16 | "include": ["src/**/*"], 17 | "references": [ 18 | { "path": "../" } 19 | ] 20 | } -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es2019", 4 | "module": "umd", 5 | "moduleResolution": "node", 6 | "sourceMap": true, 7 | "outDir": "lib", 8 | "experimentalDecorators": true, 9 | "declaration": true, 10 | "composite": true, 11 | "rootDir": "src/", 12 | "baseUrl": "./", 13 | "paths": { 14 | "*": ["onepkg/*"] 15 | } 16 | }, 17 | "include": ["src/**/*"], 18 | } -------------------------------------------------------------------------------- /typings.json: -------------------------------------------------------------------------------- 1 | { 2 | "globalDependencies": { 3 | "node": "registry:dt/node#7.0.0+20170322231424" 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /watch.sh: -------------------------------------------------------------------------------- 1 | npx tsc -b -w . test build 2 | -------------------------------------------------------------------------------- /xcompiled-src/native/CSharp/.gitignore: -------------------------------------------------------------------------------- 1 | bin/ 2 | obj/ -------------------------------------------------------------------------------- /xcompiled-src/native/CSharp/.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "name": ".NET Core Launch (console)", 9 | "type": "coreclr", 10 | "request": "launch", 11 | "preLaunchTask": "build", 12 | "program": "${workspaceFolder}/bin/Debug/netcoreapp3.0/CSharp.dll", 13 | "args": [], 14 | "cwd": "${workspaceFolder}", 15 | "console": "internalConsole", 16 | "stopAtEntry": false 17 | }, 18 | { 19 | "name": ".NET Core Attach", 20 | "type": "coreclr", 21 | "request": "attach", 22 | "processId": "${command:pickProcess}" 23 | } 24 | ] 25 | } -------------------------------------------------------------------------------- /xcompiled-src/native/CSharp/.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "2.0.0", 3 | "tasks": [ 4 | { 5 | "label": "build", 6 | "command": "dotnet", 7 | "type": "process", 8 | "args": [ 9 | "build", 10 | "${workspaceFolder}/CSharp.csproj", 11 | "/property:GenerateFullPaths=true", 12 | "/consoleloggerparameters:NoSummary" 13 | ], 14 | "problemMatcher": "$msCompile" 15 | }, 16 | { 17 | "label": "publish", 18 | "command": "dotnet", 19 | "type": "process", 20 | "args": [ 21 | "publish", 22 | "${workspaceFolder}/CSharp.csproj", 23 | "/property:GenerateFullPaths=true", 24 | "/consoleloggerparameters:NoSummary" 25 | ], 26 | "problemMatcher": "$msCompile" 27 | }, 28 | { 29 | "label": "watch", 30 | "command": "dotnet", 31 | "type": "process", 32 | "args": [ 33 | "watch", 34 | "run", 35 | "${workspaceFolder}/CSharp.csproj", 36 | "/property:GenerateFullPaths=true", 37 | "/consoleloggerparameters:NoSummary" 38 | ], 39 | "problemMatcher": "$msCompile" 40 | } 41 | ] 42 | } -------------------------------------------------------------------------------- /xcompiled-src/native/CSharp/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading.Tasks; 3 | using Generator; 4 | using Test; 5 | 6 | namespace CSharp 7 | { 8 | class Program 9 | { 10 | static async Task Main(string[] args) 11 | { 12 | await new TestRunner("../../", args).runTests(); 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /xcompiled-src/native/Java/src/main/java/Main.java: -------------------------------------------------------------------------------- 1 | import OneLang.Test.TestRunner.TestRunner; 2 | 3 | public class Main { 4 | public static void main(String[] args) { 5 | new TestRunner("../../", args).runTests(); 6 | } 7 | } -------------------------------------------------------------------------------- /xcompiled-src/native/LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Tamás Koczka 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /xcompiled-src/native/PHP/main.php: -------------------------------------------------------------------------------- 1 | runTests(); 13 | } catch(Error $e) { 14 | print($e->getMessage() . "\n"); 15 | } -------------------------------------------------------------------------------- /xcompiled-src/native/Python/main.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import os 3 | 4 | sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)) + "/onepkg") 5 | 6 | from OneLang.Test.TestRunner import TestRunner 7 | 8 | TestRunner("../../", sys.argv).run_tests() 9 | -------------------------------------------------------------------------------- /xcompiled-src/one.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "OneLang", 3 | "dependencies": [ 4 | { "name": "OneLang-Core", "version": "0.1" }, 5 | { "name": "OneLang-Console", "version": "0.1" }, 6 | { "name": "OneLang-File", "version": "0.1" }, 7 | { "name": "OneLang-Json", "version": "0.1" }, 8 | { "name": "OneLang-Yaml", "version": "0.1" }, 9 | { "name": "OneLang-Reflect", "version": "0.1" } 10 | ], 11 | "sourceDir": "../src", 12 | "sourceLang": "ts", 13 | "nativeSourceDir": "native", 14 | "outputDir": "../xcompiled", 15 | "projectTemplates": ["One.CSharp-v1", "One.Java-v1", "One.PHP-v1", "One.Python-v1"] 16 | } -------------------------------------------------------------------------------- /xcompiled-src/scripts/cleanup_generated_code.sh: -------------------------------------------------------------------------------- 1 | cd ../../xcompiled 2 | 3 | rm -rf CSharp/Generator 4 | rm -rf CSharp/One 5 | rm -rf CSharp/Parsers 6 | rm -rf CSharp/StdLib 7 | rm -rf CSharp/Test 8 | rm -rf CSharp/Utils 9 | rm -rf CSharp/bin 10 | rm -rf CSharp/obj 11 | 12 | rm -rf Java/src/main/java/OneLang 13 | rm -rf Java/.gradle 14 | rm -rf Java/bin 15 | rm -rf Java/build 16 | 17 | rm -rf PHP/src 18 | 19 | rm -rf Python/OneLang/Generator 20 | rm -rf Python/OneLang/One 21 | rm -rf Python/OneLang/Parsers 22 | rm -rf Python/OneLang/StdLib 23 | rm -rf Python/OneLang/Test 24 | rm -rf Python/OneLang/Utils 25 | rm -rf Python/__pycache__ 26 | rm -rf Python/OneLang/_external/__pycache__ 27 | rm -rf Python/onepkg/__pycache__ -------------------------------------------------------------------------------- /xcompiled-src/scripts/test_all.sh: -------------------------------------------------------------------------------- 1 | run() { 2 | set -o pipefail 3 | script -q /dev/null $(printf "%q " "$@") | grep -v "matches\|passed" 4 | } 5 | 6 | cd ../../xcompiled 7 | 8 | echo ======================= JAVASCRIPT ======================= 9 | run node --unhandled-rejections=strict ../test/lib/SelfTest.js 10 | JS=$? 11 | echo 12 | 13 | echo ======================= PHP ======================= 14 | pushd PHP > /dev/null 15 | composer dump-autoload 16 | run php main.php 17 | PHP=$? 18 | popd > /dev/null 19 | echo 20 | 21 | echo ======================= C# ======================= 22 | pushd CSharp > /dev/null 23 | run dotnet run 24 | CS=$? 25 | popd > /dev/null 26 | echo 27 | 28 | echo ======================= PYTHON ======================= 29 | pushd Python > /dev/null 30 | run python3 main.py 31 | PYTHON=$? 32 | popd > /dev/null 33 | echo 34 | 35 | echo ======================= JAVA ======================= 36 | pushd Java > /dev/null 37 | run ./gradlew run 38 | JAVA=$? 39 | popd > /dev/null 40 | echo 41 | 42 | echo JS = $JS, PHP = $PHP, C# = $CS, PYTHON = $PYTHON, JAVA = $JAVA 43 | --------------------------------------------------------------------------------