diff --git a/samples/calculator/build.gradle b/samples/calculator/build.gradle new file mode 100644 index 00000000000..cf8f754d082 --- /dev/null +++ b/samples/calculator/build.gradle @@ -0,0 +1,25 @@ +buildscript { + ext.kotlin_version = '1.2.0' + + dependencies { + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" + } +} + +apply plugin: 'kotlin' + +repositories { + mavenCentral() +} + +dependencies { + compile "org.jetbrains.kotlin:kotlin-stdlib" +} + +apply plugin: 'konan' + +konan.targets = ['iphone'] + +konanArtifacts { + framework('KotlinArithmeticParser') +} diff --git a/samples/calculator/calculator.xcodeproj/project.pbxproj b/samples/calculator/calculator.xcodeproj/project.pbxproj new file mode 100644 index 00000000000..d175f4c5461 --- /dev/null +++ b/samples/calculator/calculator.xcodeproj/project.pbxproj @@ -0,0 +1,377 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 48; + objects = { + +/* Begin PBXBuildFile section */ + 2C3F38451FD1738300151601 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C3F38441FD1738300151601 /* AppDelegate.swift */; }; + 2C3F38471FD1738300151601 /* ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2C3F38461FD1738300151601 /* ViewController.swift */; }; + 2C3F384A1FD1738300151601 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 2C3F38481FD1738300151601 /* Main.storyboard */; }; + 2C3F384C1FD1738300151601 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 2C3F384B1FD1738300151601 /* Assets.xcassets */; }; + 2C3F384F1FD1738300151601 /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 2C3F384D1FD1738300151601 /* LaunchScreen.storyboard */; }; + 2C3F385B1FD1760A00151601 /* KotlinArithmeticParser.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 2C3F385A1FD1760A00151601 /* KotlinArithmeticParser.framework */; }; + 2C3F385C1FD1760A00151601 /* KotlinArithmeticParser.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 2C3F385A1FD1760A00151601 /* KotlinArithmeticParser.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; +/* End PBXBuildFile section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 2C3F385D1FD1760A00151601 /* Embed Frameworks */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + 2C3F385C1FD1760A00151601 /* KotlinArithmeticParser.framework in Embed Frameworks */, + ); + name = "Embed Frameworks"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 2C3F38411FD1738300151601 /* calculator.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = calculator.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 2C3F38441FD1738300151601 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 2C3F38461FD1738300151601 /* ViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ViewController.swift; sourceTree = ""; }; + 2C3F38491FD1738300151601 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; + 2C3F384B1FD1738300151601 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; + 2C3F384E1FD1738300151601 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; + 2C3F38501FD1738300151601 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 2C3F385A1FD1760A00151601 /* KotlinArithmeticParser.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = KotlinArithmeticParser.framework; path = build/konan/bin/iphone/KotlinArithmeticParser.framework; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 2C3F383E1FD1738300151601 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 2C3F385B1FD1760A00151601 /* KotlinArithmeticParser.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 2C3F38381FD1738300151601 = { + isa = PBXGroup; + children = ( + 2C3F385A1FD1760A00151601 /* KotlinArithmeticParser.framework */, + 2C3F38431FD1738300151601 /* calculator */, + 2C3F38421FD1738300151601 /* Products */, + ); + sourceTree = ""; + }; + 2C3F38421FD1738300151601 /* Products */ = { + isa = PBXGroup; + children = ( + 2C3F38411FD1738300151601 /* calculator.app */, + ); + name = Products; + sourceTree = ""; + }; + 2C3F38431FD1738300151601 /* calculator */ = { + isa = PBXGroup; + children = ( + 2C3F38441FD1738300151601 /* AppDelegate.swift */, + 2C3F38461FD1738300151601 /* ViewController.swift */, + 2C3F38481FD1738300151601 /* Main.storyboard */, + 2C3F384B1FD1738300151601 /* Assets.xcassets */, + 2C3F384D1FD1738300151601 /* LaunchScreen.storyboard */, + 2C3F38501FD1738300151601 /* Info.plist */, + ); + path = calculator; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 2C3F38401FD1738300151601 /* calculator */ = { + isa = PBXNativeTarget; + buildConfigurationList = 2C3F38531FD1738300151601 /* Build configuration list for PBXNativeTarget "calculator" */; + buildPhases = ( + 2C3F38561FD1754800151601 /* Compile Kotlin Framework */, + 2C3F383D1FD1738300151601 /* Sources */, + 2C3F383E1FD1738300151601 /* Frameworks */, + 2C3F383F1FD1738300151601 /* Resources */, + 2C3F385D1FD1760A00151601 /* Embed Frameworks */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = calculator; + productName = calculator; + productReference = 2C3F38411FD1738300151601 /* calculator.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 2C3F38391FD1738300151601 /* Project object */ = { + isa = PBXProject; + attributes = { + LastSwiftUpdateCheck = 0900; + LastUpgradeCheck = 0900; + ORGANIZATIONNAME = JetBrains; + TargetAttributes = { + 2C3F38401FD1738300151601 = { + CreatedOnToolsVersion = 9.0; + ProvisioningStyle = Automatic; + }; + }; + }; + buildConfigurationList = 2C3F383C1FD1738300151601 /* Build configuration list for PBXProject "calculator" */; + compatibilityVersion = "Xcode 8.0"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 2C3F38381FD1738300151601; + productRefGroup = 2C3F38421FD1738300151601 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 2C3F38401FD1738300151601 /* calculator */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 2C3F383F1FD1738300151601 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 2C3F384F1FD1738300151601 /* LaunchScreen.storyboard in Resources */, + 2C3F384C1FD1738300151601 /* Assets.xcassets in Resources */, + 2C3F384A1FD1738300151601 /* Main.storyboard in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 2C3F38561FD1754800151601 /* Compile Kotlin Framework */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "Compile Kotlin Framework"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "$SRCROOT/../gradlew -p $SRCROOT compileKonanKotlinArithmeticParser"; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 2C3F383D1FD1738300151601 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 2C3F38471FD1738300151601 /* ViewController.swift in Sources */, + 2C3F38451FD1738300151601 /* AppDelegate.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXVariantGroup section */ + 2C3F38481FD1738300151601 /* Main.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 2C3F38491FD1738300151601 /* Base */, + ); + name = Main.storyboard; + sourceTree = ""; + }; + 2C3F384D1FD1738300151601 /* LaunchScreen.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 2C3F384E1FD1738300151601 /* Base */, + ); + name = LaunchScreen.storyboard; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 2C3F38511FD1738300151601 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + CODE_SIGN_IDENTITY = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 11.0; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + 2C3F38521FD1738300151601 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + CODE_SIGN_IDENTITY = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 11.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + 2C3F38541FD1738300151601 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CODE_SIGN_STYLE = Automatic; + DEVELOPMENT_TEAM = ""; + ENABLE_BITCODE = NO; + FRAMEWORK_SEARCH_PATHS = ( + "$(inherited)", + "$(PROJECT_DIR)/build/konan/bin/iphone", + ); + INFOPLIST_FILE = calculator/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 10.3; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = org.jetbrains.konan.calculator; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 4.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + 2C3F38551FD1738300151601 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CODE_SIGN_STYLE = Automatic; + DEVELOPMENT_TEAM = ""; + ENABLE_BITCODE = NO; + FRAMEWORK_SEARCH_PATHS = ( + "$(inherited)", + "$(PROJECT_DIR)/build/konan/bin/iphone", + ); + INFOPLIST_FILE = calculator/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 10.3; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; + PRODUCT_BUNDLE_IDENTIFIER = org.jetbrains.konan.calculator; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 4.0; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 2C3F383C1FD1738300151601 /* Build configuration list for PBXProject "calculator" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 2C3F38511FD1738300151601 /* Debug */, + 2C3F38521FD1738300151601 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 2C3F38531FD1738300151601 /* Build configuration list for PBXNativeTarget "calculator" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 2C3F38541FD1738300151601 /* Debug */, + 2C3F38551FD1738300151601 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 2C3F38391FD1738300151601 /* Project object */; +} diff --git a/samples/calculator/calculator.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/samples/calculator/calculator.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 00000000000..7527b6e65d4 --- /dev/null +++ b/samples/calculator/calculator.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/samples/calculator/calculator/AppDelegate.swift b/samples/calculator/calculator/AppDelegate.swift new file mode 100644 index 00000000000..86c713afed7 --- /dev/null +++ b/samples/calculator/calculator/AppDelegate.swift @@ -0,0 +1,46 @@ +// +// AppDelegate.swift +// calculator +// +// Created by jetbrains on 01/12/2017. +// Copyright © 2017 JetBrains. All rights reserved. +// + +import UIKit + +@UIApplicationMain +class AppDelegate: UIResponder, UIApplicationDelegate { + + var window: UIWindow? + + + func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { + // Override point for customization after application launch. + return true + } + + func applicationWillResignActive(_ application: UIApplication) { + // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. + // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. + } + + func applicationDidEnterBackground(_ application: UIApplication) { + // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. + // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. + } + + func applicationWillEnterForeground(_ application: UIApplication) { + // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. + } + + func applicationDidBecomeActive(_ application: UIApplication) { + // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. + } + + func applicationWillTerminate(_ application: UIApplication) { + // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. + } + + +} + diff --git a/samples/calculator/calculator/Assets.xcassets/AppIcon.appiconset/Contents.json b/samples/calculator/calculator/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 00000000000..1d060ed2882 --- /dev/null +++ b/samples/calculator/calculator/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,93 @@ +{ + "images" : [ + { + "idiom" : "iphone", + "size" : "20x20", + "scale" : "2x" + }, + { + "idiom" : "iphone", + "size" : "20x20", + "scale" : "3x" + }, + { + "idiom" : "iphone", + "size" : "29x29", + "scale" : "2x" + }, + { + "idiom" : "iphone", + "size" : "29x29", + "scale" : "3x" + }, + { + "idiom" : "iphone", + "size" : "40x40", + "scale" : "2x" + }, + { + "idiom" : "iphone", + "size" : "40x40", + "scale" : "3x" + }, + { + "idiom" : "iphone", + "size" : "60x60", + "scale" : "2x" + }, + { + "idiom" : "iphone", + "size" : "60x60", + "scale" : "3x" + }, + { + "idiom" : "ipad", + "size" : "20x20", + "scale" : "1x" + }, + { + "idiom" : "ipad", + "size" : "20x20", + "scale" : "2x" + }, + { + "idiom" : "ipad", + "size" : "29x29", + "scale" : "1x" + }, + { + "idiom" : "ipad", + "size" : "29x29", + "scale" : "2x" + }, + { + "idiom" : "ipad", + "size" : "40x40", + "scale" : "1x" + }, + { + "idiom" : "ipad", + "size" : "40x40", + "scale" : "2x" + }, + { + "idiom" : "ipad", + "size" : "76x76", + "scale" : "1x" + }, + { + "idiom" : "ipad", + "size" : "76x76", + "scale" : "2x" + }, + { + "idiom" : "ipad", + "size" : "83.5x83.5", + "scale" : "2x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/samples/calculator/calculator/Base.lproj/LaunchScreen.storyboard b/samples/calculator/calculator/Base.lproj/LaunchScreen.storyboard new file mode 100644 index 00000000000..f83f6fd5810 --- /dev/null +++ b/samples/calculator/calculator/Base.lproj/LaunchScreen.storyboard @@ -0,0 +1,25 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/samples/calculator/calculator/Base.lproj/Main.storyboard b/samples/calculator/calculator/Base.lproj/Main.storyboard new file mode 100644 index 00000000000..72546e9149b --- /dev/null +++ b/samples/calculator/calculator/Base.lproj/Main.storyboard @@ -0,0 +1,100 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/samples/calculator/calculator/Info.plist b/samples/calculator/calculator/Info.plist new file mode 100644 index 00000000000..89d7858b37e --- /dev/null +++ b/samples/calculator/calculator/Info.plist @@ -0,0 +1,43 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + APPL + CFBundleShortVersionString + 1.0 + CFBundleVersion + 1 + LSRequiresIPhoneOS + + UILaunchStoryboardName + LaunchScreen + UIMainStoryboardFile + Main + UIRequiredDeviceCapabilities + + armv7 + + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + + diff --git a/samples/calculator/calculator/ViewController.swift b/samples/calculator/calculator/ViewController.swift new file mode 100644 index 00000000000..efde96facde --- /dev/null +++ b/samples/calculator/calculator/ViewController.swift @@ -0,0 +1,154 @@ +// +// ViewController.swift +// calculator +// +// Created by jetbrains on 01/12/2017. +// Copyright © 2017 JetBrains. All rights reserved. +// + +import UIKit +import KotlinArithmeticParser + +class ViewController: UIViewController, UITextViewDelegate, UICollectionViewDataSource { + + override func viewDidLoad() { + super.viewDidLoad() + // Do any additional setup after loading the view, typically from a nib. + numpad.dataSource = self + self.input.delegate = self + inputDidChange() + } + + override func didReceiveMemoryWarning() { + super.didReceiveMemoryWarning() + // Dispose of any resources that can be recreated. + } + + @IBOutlet var partialResult: UILabel! + @IBOutlet var result: UILabel! + @IBOutlet var input: UITextView! + @IBOutlet var numpad: UICollectionView! + + private let parser = KAPPartialParser(composer: KAPCalculator(), partialComposer: PartialRenderer()) + + @IBAction func numpadButtonPressed(_ sender: UIButton) { + let title = sender.currentTitle! + if title == "" { + return + } + + if title == "⌫" { + if !input.text.isEmpty { + input.text.removeLast() + } + } else { + input.text.append(title) + } + + inputDidChange() + } + + func textViewDidChange(_ textView: UITextView) { + if textView === input { + inputDidChange() + } + } + + override func touchesBegan(_ touches: Set, with event: UIEvent?) { + self.input.endEditing(true) + } + + private func inputDidChange() { + let parsed = parser.parseWithPartial(expression: input.text) + if let resultValue = parsed.expression { + result.text = "= \(resultValue)" + } else { + result.text = "" + } + + let attributedText = parsed.partialExpression as! NSAttributedString + + if let remainder = parsed.remainder { + partialResult.attributedText = attributedText + + NSAttributedString(string: " ") + + NSAttributedString(string: remainder, attributes: + [.foregroundColor: UIColor.red, + .font: UIFont.boldSystemFont(ofSize: partialResult.font.pointSize)]) + } else { + partialResult.attributedText = attributedText + } + } + + private let buttons = [ + "7", "8", "9", "/", + "4", "5", "6", "*", + "1", "2", "3", "-", + ".", "0", "", "+", + "(", ")", "", "⌫" + ] + + func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { + return buttons.count + } + + func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { + let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "buttonCell", for: indexPath) + + (cell.viewWithTag(1) as! UIButton).setTitle(buttons[indexPath.item],for: .normal) + + return cell + } +} + +private func +(left: NSAttributedString, right: NSAttributedString) -> NSAttributedString { + let result = NSMutableAttributedString(attributedString: left) + result.append(right) + return result +} + +private extension String { + func toAttributed() -> NSAttributedString { + return NSAttributedString(string: self) + } +} + +private class PartialRenderer: NSObject, KAPPartialExpressionComposer { + func missing() -> Any { + return "... ".toAttributed() + } + + func ending(expression: Any) -> Any { + return "\(formatDouble(expression))... ".toAttributed() + } + + func plus(left: Any, partialRight: Any) -> Any { + return compose("+", left, partialRight) + } + + func minus(left: Any, partialRight: Any) -> Any { + return compose("-", left, partialRight) + } + + func mult(left: Any, partialRight: Any) -> Any { + return compose("*", left, partialRight) + } + + func div(left: Any, partialRight: Any) -> Any { + return compose("/", left, partialRight) + } + + func leftParenthesized(partialExpression: Any) -> Any { + let suffix = NSAttributedString(string: ")", attributes: [.foregroundColor: UIColor.lightGray]) + return "(".toAttributed() + (partialExpression as! NSAttributedString) + suffix + } + + private func formatDouble(_ value: Any) -> String { + let rounded = round(1000 * (value as! Double)) / 1000 + return "\(rounded as NSNumber)" + } + + private func compose(_ op: String, _ left: Any, _ partialRight: Any) -> Any { + return "\(formatDouble(left)) \(op) ".toAttributed() + (partialRight as! NSAttributedString) + } + +} diff --git a/samples/calculator/src/main/kotlin/org/konan/arithmeticparser/Parser.kt b/samples/calculator/src/main/kotlin/org/konan/arithmeticparser/Parser.kt new file mode 100644 index 00000000000..02e19ac6f1a --- /dev/null +++ b/samples/calculator/src/main/kotlin/org/konan/arithmeticparser/Parser.kt @@ -0,0 +1,297 @@ +/* + * Copyright 2010-2017 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.konan.arithmeticparser + +fun parseAndCompute(expression: String): PartialParser.Result = + PartialParser(Calculator(), PartialRenderer()).parseWithPartial(expression) + +class Calculator : ExpressionComposer { + override fun number(value: Double) = value + override fun plus(left: Double, right: Double) = left + right + override fun minus(left: Double, right: Double) = left - right + override fun mult(left: Double, right: Double) = left * right + override fun div(left: Double, right: Double) = left / right +} + +class PartialRenderer : PartialExpressionComposer { + override fun missing() = "..." + + override fun ending(expression: Double) = "$expression ..." + + override fun plus(left: Double, partialRight: String) = "$left + $partialRight" + override fun minus(left: Double, partialRight: String) = "$left - $partialRight" + override fun mult(left: Double, partialRight: String) = "$left * $partialRight" + override fun div(left: Double, partialRight: String) = "$left / $partialRight" + override fun leftParenthesized(partialExpression: String) = "($partialExpression" +} + +interface ExpressionComposer { + fun number(value: Double): E + fun plus(left: E, right: E): E + fun minus(left: E, right: E): E + fun mult(left: E, right: E): E + fun div(left: E, right: E): E +} + +open class Parser(protected val composer: ExpressionComposer) { + fun parse(expression: String): E? { + val tokenizer = Tokenizer(expression) + val prefix = parseAsPrefix(tokenizer) + + if (prefix is EndedWithExpression && !tokenizer.hasNext()) { + val reduced = prefix.reduced() + if (reduced.prefix is Empty) { + return reduced.expression + } + } + + return null + } + + internal fun parseAsPrefix(tokenizer: Tokenizer): ExpressionPrefix = + generateSequence>(Empty) { + it.tryExtend(tokenizer) + }.last() + + private fun ExpressionPrefix.tryExtend(tokenizer: Tokenizer): ExpressionPrefix? = when (this) { + is ContinuableWithExpression -> { + val number = tokenizer.tryReadNumber() + if (number != null) { + this.with(composer.number(number)) + } else if (tokenizer.tryReadLeftParenthesis()) { + this.withLeftParenthesis() + } else { + null + } + } + + is EndedWithExpression -> { + val operator = tokenizer.tryReadBinaryOperator() + if (operator != null) { + this.extendedWithOperator(operator) + } else { + val reduced = this.reduced() + if (reduced.prefix is EndedWithLeftParenthesis && tokenizer.tryReadRightParenthesis()) { + // Drop parens: + reduced.prefix.prefix.with(reduced.expression) + } else { + null + } + } + } + } + + private tailrec fun EndedWithExpression.extendedWithOperator(operator: BinaryOperator): EndedWithOperator = + if (this.prefix is EndedWithOperator && this.prefix.operator.precedence >= operator.precedence) { + // Apply the operator + this.prefix + .withOperatorApplied(this.expression) + .extendedWithOperator(operator) + } else { + EndedWithOperator(this.prefix, this.expression, operator) + } + + internal tailrec fun EndedWithExpression.reduced(): EndedWithExpression = when (this.prefix) { + Empty, is EndedWithLeftParenthesis -> this + + is EndedWithOperator -> + this.prefix + .withOperatorApplied(this.expression) + .reduced() + } + + private fun EndedWithOperator.withOperatorApplied(rightOperand: E) = + this.prefix.with(composer.compose(this.operator, this.leftOperand, rightOperand)) + + private fun ExpressionComposer.compose( + binaryOperator: BinaryOperator, left: E, right: E + ): E = when (binaryOperator) { + BinaryOperator.PLUS -> plus(left, right) + BinaryOperator.MINUS -> minus(left, right) + BinaryOperator.MULT -> mult(left, right) + BinaryOperator.DIV -> div(left, right) + } + +} + +interface PartialExpressionComposer { + fun missing(): PE + fun ending(expression: E): PE + + fun plus(left: E, partialRight: PE): PE + fun minus(left: E, partialRight: PE): PE + fun mult(left: E, partialRight: PE): PE + fun div(left: E, partialRight: PE): PE + + fun leftParenthesized(partialExpression: PE): PE +} + +class PartialParser( + composer: ExpressionComposer, + private val partialComposer: PartialExpressionComposer +) : Parser(composer) { + + data class Result(val expression: E?, val partialExpression: PE, val remainder: String?) + + fun parseWithPartial(expression: String): Result { + val tokenizer = Tokenizer(expression) + val prefix = parseAsPrefix(tokenizer) + + val remainder = tokenizer.getRemainder() + + return Result( + if (remainder != null) null else tryReduce(prefix), + prefix.toPartialExpression(), + remainder + ) + } + + private fun tryReduce(prefix: ExpressionPrefix): E? { + if (prefix is EndedWithExpression) { + val reduced = prefix.reduced() + if (reduced.prefix is Empty) { + return reduced.expression + } + } + + return null + } + + private fun ExpressionPrefix.toPartialExpression(): PE = when (this) { + is EndedWithExpression -> this.prefix.toPartialExpressionWith( + ending = partialComposer.ending(this.expression) + ) + is ContinuableWithExpression -> this.toPartialExpressionWith(ending = partialComposer.missing()) + } + + private tailrec fun ContinuableWithExpression.toPartialExpressionWith( + ending: PE + ): PE = when (this) { + Empty -> ending + + is EndedWithLeftParenthesis -> this.prefix.toPartialExpressionWith( + ending = partialComposer.leftParenthesized(ending) + ) + + is EndedWithOperator -> this.prefix.toPartialExpressionWith( + ending = partialComposer.compose(this.operator, this.leftOperand, ending) + ) + } + + private fun PartialExpressionComposer.compose( + binaryOperator: BinaryOperator, + left: E, + right: PE + ): PE = when (binaryOperator) { + BinaryOperator.PLUS -> plus(left, right) + BinaryOperator.MINUS -> minus(left, right) + BinaryOperator.MULT -> mult(left, right) + BinaryOperator.DIV -> div(left, right) + } +} + +/** + * Immutable prefix of expression partially parsed to combination of abstractly represented expressions. + * The prefix representation can be thought as "almost AST", i.e. AST with unfinished rightmost leaf + * (referenced by this object), and its nodes contain links to parent and (if needed) left child. + * + * @param E abstract representation of expression, e.g. its value, AST etc. + */ +internal sealed class ExpressionPrefix + +internal data class EndedWithExpression( + val prefix: ContinuableWithExpression, + val expression: E +) : ExpressionPrefix() + +internal sealed class ContinuableWithExpression : ExpressionPrefix() + +private fun ContinuableWithExpression.with(expression: E) = + EndedWithExpression(this, expression) + +private object Empty : ContinuableWithExpression() + +private data class EndedWithLeftParenthesis( + val prefix: ContinuableWithExpression +) : ContinuableWithExpression() + +private fun ContinuableWithExpression.withLeftParenthesis() = + EndedWithLeftParenthesis(this) + +private data class EndedWithOperator( + val prefix: ContinuableWithExpression, + val leftOperand: E, + val operator: BinaryOperator +) : ContinuableWithExpression() + +internal enum class BinaryOperator(val sign: Char, val precedence: Int) { + PLUS('+', 2), + MINUS('-', 2), + MULT('*', 3), + DIV('/', 3) +} + +internal class Tokenizer(private val expression: String) { + private var index = 0 + + init { + skipSpaces() + } + + fun hasNext(): Boolean = (index < expression.length) + + fun getRemainder(): String? = if (this.hasNext()) { + expression.substring(index) + } else { + null + } + + fun tryReadNumber(): Double? { + var endIndex = index + while (expression.getOrNull(endIndex)?.isNumberChar() == true) { + ++endIndex + } + + return expression.substring(index, endIndex).toDoubleOrNull()?.also { + index = endIndex + skipSpaces() + } + } + + private fun Char.isNumberChar(): Boolean = this.isDigit() || this == '.' + + fun tryReadBinaryOperator(): BinaryOperator? = BinaryOperator.values().firstOrNull { tryRead(it.sign) } + + fun tryReadLeftParenthesis(): Boolean = tryRead('(') + + fun tryReadRightParenthesis(): Boolean = tryRead(')') + + + private fun tryRead(char: Char): Boolean = if (hasNext() && expression[index] == char) { + ++index + skipSpaces() + true + } else { + false + } + + private fun skipSpaces() { + while (expression.getOrNull(index)?.isWhitespace() == true) { + ++index + } + } +} diff --git a/samples/settings.gradle b/samples/settings.gradle index 639116634fa..726fa3b3165 100644 --- a/samples/settings.gradle +++ b/samples/settings.gradle @@ -1,3 +1,4 @@ +include ':calculator' include ':csvparser' include ':gitchurn' include ':gtk'