def run (sourcePath): def logHeader (sourcePath): utils.log (True, 'Performing static type validation on application: {}\n', sourcePath) try: options = Options () # options.silent_imports = True result = main.type_check_only ([BuildSource (sourcePath, None, None)], None, options) if result.errors: logHeader (sourcePath) oldModuleName = '' for message in result.errors: if ': error:' in message: moduleName, lineNr, errorLabel, tail = message.split (':', 4) if moduleName != oldModuleName: utils.log (True, '\tFile {}\n', moduleName) oldModuleName = moduleName utils.log (True, '\t\tLine {}:{}\n', lineNr, tail) utils.log (True, '\n') except CompileError as compileError: if compileError.messages: logHeader (sourcePath) for message in compileError.messages: utils.log (True, '\t{}', message) utils.log (True, '\n')
def run(sourcePath): def logHeader(sourcePath): utils.log(True, 'Performing static type validation on application: {}\n', sourcePath) try: options = Options() # options.silent_imports = True result = main.type_check_only([BuildSource(sourcePath, None, None)], None, options) if result.errors: logHeader(sourcePath) oldModuleName = '' for message in result.errors: if ': error:' in message: moduleName, lineNr, errorLabel, tail = message.split( ':', 4) if moduleName != oldModuleName: utils.log(True, '\tFile {}\n', moduleName) oldModuleName = moduleName utils.log(True, '\t\tLine {}:{}\n', lineNr, tail) utils.log(True, '\n') except CompileError as compileError: if compileError.messages: logHeader(sourcePath) for message in compileError.messages: utils.log(True, '\t{}', message) utils.log(True, '\n')
def extract (self): utils.log (False, 'Extracting metadata from: {}\n', self.metadata.targetPath) useFragment = self.targetCode [self.targetCode.rfind ('<use>') : self.targetCode.rfind ('</use>')] self.use = sorted (set ([ word for word in useFragment.replace ('__pragma__', ' ') .replace ('(', ' ') .replace (')', ' ') .replace ('\'', ' ') .replace ('+', ' ') .split () if not word.startswith ('<') ])) for moduleName in self.use: self.program.provide (moduleName) allFragment = self.targetCode [self.targetCode.rfind ('<all>') : self.targetCode.rfind ('</all>')] self.all = sorted (set ([ word [1 : ] for word in allFragment.replace ('__all__', ' ') .replace ('=', ' ') .split () if word.startswith ('.') ])) extraLines = [ '__pragma__ = 0', # No code will be emitted for pragma's anyhow '__pragma__ (\'skip\')', # Here __pragma__ must already be a known name for the static_check '__new__ = __include__ = 0', '__pragma__ (\'noskip\')' '' ] if utils.commandArgs else [] nrOfExtraLines = max (len (extraLines) - 1, 0) # Last line only to force linefeed extraLines = '\n'.join (extraLines)
def extract (self): utils.log (False, 'Extracting metadata from: {}\n', self.metadata.targetPath) allFragment = self.targetCode [self.targetCode.rfind ('<all>') : self.targetCode.rfind ('</all>')] self.all = sorted (set ([ word [1 : ] for word in allFragment.replace ('__all__', ' ') .replace ('=', ' ') .split () if word.startswith ('.') ])) # So skip the words 'var' and 'return'
def compile (self): # Define names early, since they are cross-used in module compilation prefix = 'org.{}'.format (__base__.__envir__.transpilerName) self.coreModuleName = '{}.{}'.format (prefix, '__core__') self.baseModuleName = '{}.{}'.format (prefix, '__base__') self.standardModuleName = '{}.{}'.format (prefix, '__standard__') self.builtinModuleName = '{}.{}'.format (prefix, '__builtin__') self.mainModuleName = self.sourceFileName [ : -3] # Module compilation Module (self, ModuleMetadata (self, self.coreModuleName)) Module (self, ModuleMetadata (self, self.baseModuleName)) Module (self, ModuleMetadata (self, self.standardModuleName)) Module (self, ModuleMetadata (self, self.builtinModuleName)) try: moduleMetadata = ModuleMetadata (self, self.mainModuleName) Module (self, moduleMetadata) # Will trigger recursive compilation except Exception as exception: utils.enhanceException ( exception, message = str (exception) ) # Join all non-inline modules normallyImportedTargetCode = ''.join ([ self.moduleDict [moduleName] .targetCode for moduleName in sorted (self.moduleDict) if not moduleName in (self.coreModuleName, self.baseModuleName, self.standardModuleName, self.builtinModuleName, self.mainModuleName) ]) # And sandwich them between the in-line modules targetCode = ( self.header + 'function {} () {{\n'.format (self.mainModuleName) + self.moduleDict [self.coreModuleName].targetCode + self.moduleDict [self.baseModuleName] .targetCode + self.moduleDict [self.standardModuleName] .targetCode + self.moduleDict [self.builtinModuleName].targetCode + normallyImportedTargetCode + self.moduleDict [self.mainModuleName].targetCode + ' return __all__;\n' + '}\n' + 'window [\'{0}\'] = {0} ();\n'.format (self.mainModuleName) ) targetFileName = '{}/{}.js'.format ('{}/{}'.format (self.sourceDir, __base__.__envir__.targetSubDir), self.mainModuleName) utils.log (False, 'Saving result in: {}\n', targetFileName) with utils.create (targetFileName) as aFile: aFile.write (targetCode) miniFileName = '{}/{}/{}.min.js'.format (self.sourceDir, __base__.__envir__.targetSubDir, self.mainModuleName) utils.log (False, 'Saving minified result in: {}\n', miniFileName) if not utils.commandArgs.nomin: minify.run (targetFileName, miniFileName)
def parse (self): utils.log (False, 'Parsing module: {}\n', self.metadata.sourcePath) with open (self.metadata.sourcePath) as sourceFile: self.sourceCode = sourceFile.read () self.parseTree = None if not self.parseTree: self.parseTree = ast.parse (self.sourceCode)
def loadJavascript (self): utils.log (False, 'Loading precompiled module: {}\n', self.metadata.targetPath) with open (self.metadata.targetPath) as aFile: self.targetCode = aFile.read () if self.metadata.name in (self.program.coreModuleName, self.program.builtinModuleName): # Remove comment-like line tails and empty lines (so no // inside a string allowed) self.targetCode = '{}\n'.format ( '\n'.join ([line for line in [line.split ('//') [0] .rstrip () for line in self.targetCode.split ('\n')] if line]) )
def dump (self): utils.log (False, 'Dumping syntax tree of module: {}\n', self.metadata.sourcePath) def walk (name, value, tabLevel): self.treeFragments .append ('\n{0}{1}: {2} '.format (tabLevel * '\t', name, type (value).__name__ )) if isinstance (value, ast.AST): for field in ast.iter_fields (value): walk (field [0], field [1], tabLevel + 1) elif isinstance (value, list): for element in value: walk ('element', element, tabLevel + 1) else: self.treeFragments.append ('= {0}'.format (value)) self.treeFragments = [] walk ('file', self.parseTree, 0) self.textTree = ''.join (self.treeFragments) [1:] with utils.create ('{}/{}.tree'.format (self.metadata.targetDir, self.metadata.filePrename)) as treeFile: treeFile.write (self.textTree)
def run (sourcePath): try: utils.log (True, 'Performing static type validation on application: {}\n', sourcePath) for line in api.run (sourcePath): utils.log (True, line) utils.log (True, '\n') except Exception as exception: print (traceback.format_exc ()) utils.log (False, traceback.format_exc ()) raise exception
def parse (self): try: utils.log (False, 'Parsing module: {}\n', self.metadata.sourcePath) with open (self.metadata.sourcePath) as sourceFile: self.sourceCode = utils.extraLines + sourceFile.read () self.parseTree = ast.parse (self.sourceCode) except SyntaxError as syntaxError: utils.enhanceException ( syntaxError, moduleName = self.metadata.name, lineNr = syntaxError.lineno, message = ( '{} <SYNTAX FAULT] {}'.format ( syntaxError.text [:syntaxError.offset].lstrip (), syntaxError.text [syntaxError.offset:].rstrip () ) if syntaxError.text else syntaxError.args [0] ) )
def run(sourcePath): try: utils.log(True, 'Performing static type validation on application: {}\n', sourcePath) for line in api.run(sourcePath): utils.log(True, line) utils.log(True, '\n') except Exception as exception: print(traceback.format_exc()) utils.log(False, traceback.format_exc()) raise exception
def run (sourceFile, parseTree): messageHolders = sorted ( pyflakes.checker.Checker (parseTree, sourceFile) .messages, key = lambda messageHolder: 10000 * messageHolder.lineno + messageHolder.col ) utils.log (messageHolders or utils.commandArgs.verbose, 'Checking: {}'.format (sourceFile)) if messageHolders: for messageHolder in messageHolders: utils.log (True, '\n\tLine {}: {}'.format ( messageHolder.lineno - utils.nrOfExtraLines, messageHolder.message % messageHolder.message_args )) utils.log (True, '\n') else: utils.log (utils.commandArgs.verbose, ' OK\n')
def run(sourceFile, parseTree): messageHolders = sorted(pyflakes.checker.Checker(parseTree, sourceFile).messages, key=lambda messageHolder: 10000 * messageHolder. lineno + messageHolder.col) utils.log(messageHolders or utils.commandArgs.verbose, 'Checking: {}'.format(sourceFile)) if messageHolders: for messageHolder in messageHolders: utils.log( True, '\n\tLine {}: {}'.format( messageHolder.lineno - utils.nrOfExtraLines, messageHolder.message % messageHolder.message_args)) utils.log(True, '\n') else: utils.log(utils.commandArgs.verbose, ' OK\n')
def main (): exitCode = exitCommandArgsError def exitHandler (): if exitCode == exitSuccess: utils.log (True, '\nReady\n') else: utils.log (True, '\nAborted\n') atexit.register (exitHandler) def setExitCode (anExitCode): nonlocal exitCode exitCode = anExitCode return exitCode try: licensePath = '{}/{}'.format (transpilerDir, 'license_reference.txt') if not os.path.isfile (licensePath): utils.log (True, 'Error: missing license reference file\n') return setExitCode (exitNoLicense) utils.log (True, '{} (TM) Python to JavaScript Small Sane Subset Transpiler Version {}\n', __base__.__envir__.transpiler_name.capitalize (), __base__.__envir__.transpiler_version) utils.log (True, 'Copyright (C) Geatec Engineering. License: Apache 2.0\n\n') utils.commandArgs.parse () if utils.commandArgs.license: with open (licensePath) as licenseFile: bar = 80 * '*' utils.log (True, '\n{}\n\n', bar) utils.log (True, '{}\n', licenseFile.read ()) utils.log (True, '{}\n\n', bar) if not utils.commandArgs.source: return setExitCode (exitSourceNotGiven) # Should never be here, dealth with by command arg checks already if utils.commandArgs.run: try: with open (utils.commandArgs.source) as sourceFile: exec (sourceFile.read ()) return setExitCode (exitSuccess) except Exception as exception: utils.log (True, 'Error: cannot run {} using CPython: {}\n'.format (utils.commandArgs.source, str (exception) .replace (' (<string>', '') .replace (')', ''))) return setExitCode (exitCannotRunSource) else: try: compiler.Program (compilerPath) return setExitCode (exitSuccess) except utils.Error as error: utils.log (True, '\n{}\n', error) # Don't log anything else, even in verbose mode, since this would only be confusing if utils.commandArgs.dextex: utils.log (True, '{}\n', traceback.format_exc ()) return setExitCode (exitSpecificCompileError) except Exception as exception: utils.log (True, '\n{}', exception) # Have to log something else, because a general exception isn't informative enough utils.log (True, '{}\n', traceback.format_exc ()) return setExitCode (exitGeneralCompileError) except utils.CommandArgsError: return setExitCode (exitCommandArgsError) except utils.CommandArgsExit: return setExitCode (exitSuccess)
def main (): import os import sys import traceback import site programDir = os.getcwd () .replace ('\\', '/') transpilerDir = os.path.dirname (os.path.abspath (__file__)) .replace ('\\', '/') modulesDir = '{}/modules'.format (transpilerDir) # Both CPython and Transcrypt will use all dirs in sys.path as search roots for modules # CPython will also search relatively from each module, Transcrypt only from the main module sys.path = [programDir, modulesDir] + sys.path # Under Linux sys.path does not always contain programDir sys.modules.pop ('org', None) # Unload org from a packages dir, if it's there. from org.transcrypt import __base__ # May reload org from a packages dir (or load org from different location) from org.transcrypt import utils from org.transcrypt import compiler licensePath = '{}/{}'.format (transpilerDir, 'license_reference.txt') if not os.path.isfile (licensePath): utils.log (True, 'Error: missing license reference file\n') return utils.log (True, '{} (TM) Python to JavaScript Small Sane Subset Transpiler Version {}\n', __base__.__envir__.transpiler_name.capitalize (), __base__.__envir__.transpiler_version) utils.log (True, 'Copyright (C) Geatec Engineering. License: Apache 2.0\n\n') utils.commandArgs.parse () if utils.commandArgs.license: with open (licensePath) as licenseFile: bar = 80 * '*' utils.log (True, '\n{}\n\n', bar) utils.log (True, '{}\n', licenseFile.read ()) utils.log (True, '{}\n\n', bar) if not utils.commandArgs.source: return if utils.commandArgs.run: with open (utils.commandArgs.source) as sourceFile: exec (sourceFile.read ()) else: try: compiler.Program (sys.path) except utils.Error as error: utils.log (True, '\n{}\n', error) # Don't log anything else, even in verbose mode, since this would only be confusing if utils.debug: utils.log (True, '{}\n', traceback.format_exc ()) except Exception as exception: utils.log (True, '\n{}', exception) # Have to log something else, because a general exception isn't informative enough utils.log (False, '{}\n', traceback.format_exc ()) utils.log (True, 'Ready\n')
def main(): exitCode = exitCommandArgsError def exitHandler(): if exitCode == exitSuccess: utils.log(True, '\nReady\n') else: utils.log(True, '\nAborted\n') atexit.register(exitHandler) def setExitCode(anExitCode): nonlocal exitCode exitCode = anExitCode return exitCode try: licensePath = '{}/{}'.format(transpilerDir, 'license_reference.txt') if not os.path.isfile(licensePath): utils.log(True, 'Error: missing license reference file\n') return setExitCode(exitNoLicense) utils.log( True, '{} (TM) Python to JavaScript Small Sane Subset Transpiler Version {}\n', __base__.__envir__.transpiler_name.capitalize(), __base__.__envir__.transpiler_version) utils.log(True, 'Copyright (C) Geatec Engineering. License: Apache 2.0\n\n') utils.commandArgs.parse() if utils.commandArgs.license: with open(licensePath) as licenseFile: bar = 80 * '*' utils.log(True, '\n{}\n\n', bar) utils.log(True, '{}\n', licenseFile.read()) utils.log(True, '{}\n\n', bar) if utils.commandArgs.star: webbrowser.open('https://github.com/JdeH/Transcrypt') if not utils.commandArgs.source: return setExitCode( exitSourceNotGiven ) # Should never be here, dealth with by command arg checks already __symbols__ = utils.commandArgs.symbols.split( '$') if utils.commandArgs.symbols else [] if utils.commandArgs.complex: __symbols__.append('__complex__') __symbols__.append('__py{}.{}__'.format(*sys.version_info[:2])) if utils.commandArgs.esv: __symbols__.append('__esv{}__'.format(utils.commandArgs.esv)) else: __symbols__.append('__esv{}__'.format( utils.defaultJavaScriptVersion)) from org.transcrypt.stubs.browser import __set_stubsymbols__ # Import (ignored when transpiling) late, since commandArgs must be set already __set_stubsymbols__( __symbols__ ) # Make symbols available to CPython, seems that exec can't do that directly if utils.commandArgs.run: try: with open(utils.commandArgs.source) as sourceFile: exec(sourceFile.read()) return setExitCode(exitSuccess) except Exception as exception: utils.log( True, 'Error: cannot run {} using CPython: {}\n'.format( utils.commandArgs.source, str(exception).replace(' (<string>', '').replace(')', ''))) utils.log(True, traceback.format_exc()) return setExitCode(exitCannotRunSource) else: try: compiler.Program(compilerPath, __symbols__) return setExitCode(exitSuccess) except utils.Error as error: utils.log(True, '\n{}\n', error) # Don't log anything else, even in verbose mode, since this would only be confusing if utils.commandArgs.dextex: utils.log(True, '{}\n', traceback.format_exc()) return setExitCode(exitSpecificCompileError) except Exception as exception: utils.log(True, '\n{}', exception) # Have to log something else, because a general exception isn't informative enough utils.log(True, '{}\n', traceback.format_exc()) return setExitCode(exitGeneralCompileError) except utils.CommandArgsError: return setExitCode(exitCommandArgsError) except utils.CommandArgsExit: return setExitCode(exitSuccess)
def exitHandler(): if exitCode == exitSuccess: utils.log(True, '\nReady\n') else: utils.log(True, '\nAborted\n')
def main (): exitCode = exitCommandArgsError def exitHandler (): if exitCode == exitSuccess: utils.log (True, '\nReady\n') else: utils.log (True, '\nAborted\n') atexit.register (exitHandler) def setExitCode (anExitCode): nonlocal exitCode exitCode = anExitCode return exitCode try: utils.log (True, '\n') licensePath = '{}/{}'.format (transpilerDir, 'license_reference.txt') if not os.path.isfile (licensePath): utils.log (True, 'Error: missing license reference file\n') return setExitCode (exitNoLicense) utils.log (True, '{} (TM) Python to JavaScript Small Sane Subset Transpiler Version {}\n', __base__.__envir__.transpiler_name.capitalize (), __base__.__envir__.transpiler_version) utils.log (True, 'Copyright (C) Geatec Engineering. License: Apache 2.0\n\n') utils.commandArgs.parse () if utils.commandArgs.license: with open (licensePath) as licenseFile: bar = 80 * '*' utils.log (True, '\n{}\n\n', bar) utils.log (True, '{}\n', licenseFile.read ()) utils.log (True, '{}\n\n', bar) if utils.commandArgs.star: webbrowser.open ('https://github.com/qquick/Transcrypt') if not utils.commandArgs.source: return setExitCode (exitSourceNotGiven) # Should never be here, dealth with by command arg checks already __symbols__ = utils.commandArgs.symbols.split ('$') if utils.commandArgs.symbols else [] if utils.commandArgs.complex: __symbols__.append ('__complex__') __symbols__.append ('__py{}.{}__'.format (* sys.version_info [:2])) if utils.commandArgs.esv: __symbols__.append ('__esv{}__'.format (utils.commandArgs.esv)) else: __symbols__.append ('__esv{}__'.format (utils.defaultJavaScriptVersion)) from org.transcrypt.stubs.browser import __set_stubsymbols__ # Import (ignored when transpiling) late, since commandArgs must be set already __set_stubsymbols__ (__symbols__) # Make symbols available to CPython, seems that exec can't do that directly if utils.commandArgs.run: try: with open (utils.commandArgs.source) as sourceFile: exec (sourceFile.read ()) return setExitCode (exitSuccess) except Exception as exception: utils.log (True, 'Error: cannot run {} using CPython: {}\n'.format (utils.commandArgs.source, str (exception) .replace (' (<string>', '') .replace (')', ''))) utils.log (True, traceback.format_exc()) return setExitCode (exitCannotRunSource) else: try: compiler.Program (compilerPath, __symbols__) return setExitCode (exitSuccess) except utils.Error as error: utils.log (True, '\n{}\n', error) # Don't log anything else, even in verbose mode, since this would only be confusing if utils.commandArgs.dextex: utils.log (True, '{}\n', traceback.format_exc ()) return setExitCode (exitSpecificCompileError) except Exception as exception: utils.log (True, '\n{}', exception) # Have to log something else, because a general exception isn't informative enough utils.log (True, '{}\n', traceback.format_exc ()) return setExitCode (exitGeneralCompileError) except utils.CommandArgsError: return setExitCode (exitCommandArgsError) except utils.CommandArgsExit: return setExitCode (exitSuccess)
def run(sourcePath): try: utils.log(True, 'Performing static type validation on application: {}\n', sourcePath) validationMessages = api.type_validator.validate([sourcePath]) if validationMessages: oldFileName = '' for validationMessage in validationMessages: if isinstance(validationMessage, api.StaticTypingError): if validationMessage.file_name != oldFileName: utils.log(True, '\tFile {}\n', validationMessage.file_name) oldFileName = validationMessage.file_name utils.log(True, '\t\tLine {}: {}\n', validationMessage.line_nr, validationMessage.description) elif isinstance(validationError, api.CompilationError): utils.log(True, '\t{}'.format(message)) else: util.log(True, '\tUnknown error') utils.log(True, '\n') except Exception as exception: utils.log(False, traceback.format_exc()) raise exception
def generateMultilevelMap(self): utils.log(False, 'Saving multi-level sourcemap in: {}\n' ) # !!! , 'self.mapPath') self.loadShrinkMap() self.cascadeAndSaveMiniMap()
import transcrypt.__main__ import sys, os sys.path.append (os.path.join(os.path.abspath(transcrypt.__main__.__file__), "modules")) from org.transcrypt import utils from org.transcrypt import compiler try: compiler.Program (transpilationDirs, __symbols__, __envir__) return setExitCode (exitSuccess) except utils.Error as error: utils.log (True, '\n{}\n', error) # Don't log anything else, even in verbose mode, since this would only be confusing if utils.commandArgs.dextex: utils.log (True, '{}\n', traceback.format_exc ()) return setExitCode (exitSpecificCompileError) except Exception as exception: utils.log (True, '\n{}', exception) # Have to log something else, because a general exception isn't informative enough utils.log (True, '{}\n', traceback.format_exc ()) return setExitCode (exitGeneralCompileError)
def run (sourcePath): utils.log (True, 'Performing static type validation on application: {}\n', sourcePath) try: stdOutReport, stdErrReport, exitStatus = api.run ([ sourcePath ]) except Exception as exception: print (exception) if stdOutReport: utils.log (True, 'The following inconsistencies were found:\n') for stdOutLine in stdOutReport.split ('\n'): utils.log (True, '\t{}\n', stdOutLine) if stdErrReport: utils.log (True, 'Problems encountered during static type check\n') for stdErrLine in stdErrReport.split ('\n'): utils.log (True, '\t{}\n', stdErrLine) utils.log (True, '\n')
import sys import traceback sys.path [0] = sys.path [0] + '/modules' from org.transcrypt import __base__ from org.transcrypt import utils from org.transcrypt import compiler programDir = os.getcwd () .replace ('\\', '/') transpilerDir = os.path.dirname (os.path.abspath (__file__)) .replace ('\\', '/') modulesDir = '{}/modules'.format (transpilerDir) licencePath = '{}/{}'.format (transpilerDir, '../license_reference.txt') if not os.path.isfile (licencePath): utils.log (True, 'Error: missing license reference file\n') exit (1) utils.log (True, '{} (TM) Python to JavaScript Small Sane Subset Transpiler Version {}\n', __base__.__envir__.transpilerName.capitalize (), __base__.__envir__.transpilerVersion) utils.log (True, 'Copyright (C) Geatec Engineering. License: Apache 2.0\n\n') utils.commandArgs.parse () if utils.commandArgs.license: with open (licensePath) as licenseFile: bar = 80 * '=' utils.log (True, '\n{}\n\n', bar) utils.log (True, '{}\n', licenseFile.read ()) utils.log (True, '{}\n\n', bar) if not utils.commandArgs.source:
def logHeader(sourcePath): utils.log(True, 'Performing static type validation on application: {}\n', sourcePath)
def run(sourcePath): utils.log(True, 'Performing static type validation on application: {}\n', sourcePath) try: stdOutReport, stdErrReport, exitStatus = api.run([sourcePath]) except Exception as exception: print(exception) if stdOutReport: utils.log(True, 'The following inconsistencies were found:\n') for stdOutLine in stdOutReport.split('\n'): utils.log(True, '\t{}\n', stdOutLine) if stdErrReport: utils.log(True, 'Problems encountered during static type check\n') for stdErrLine in stdErrReport.split('\n'): utils.log(True, '\t{}\n', stdErrLine) utils.log(True, '\n')
def exitHandler (): if exitCode == exitSuccess: utils.log (True, '\nReady\n') else: utils.log (True, '\nAborted\n')
def generate (self): utils.log (False, 'Generating code for module: {}\n', self.metadata.targetPath) self.targetCode = ''.join (Generator (self) .targetFragments) with utils.create (self.metadata.targetPath) as targetFile: targetFile.write (self.targetCode)
def main (): import os import sys import traceback import site programDir = os.getcwd () .replace ('\\', '/') transpilerDir = os.path.dirname (os.path.abspath (__file__)) .replace ('\\', '/') modulesDir = '{}/modules'.format (transpilerDir) # Both CPython and Transcrypt will use all dirs in sys.path as search roots for modules # CPython will also search relatively from each module, Transcrypt only from the main module compilerPath = [programDir, modulesDir] + sys.path # Used by Transcrypt rather than CPython, programDir isn't always part of the path under Linux sys.path = sys.path [1:] + [modulesDir] # Used by CPython, leave out current dir to prevent importing modules root if there's a module by that name sys.modules.pop ('org', None) # Unload org from a packages dir, if it's there. from org.transcrypt import __base__ # May reload org from a packages dir (or load org from different location) from org.transcrypt import utils from org.transcrypt import compiler licensePath = '{}/{}'.format (transpilerDir, 'license_reference.txt') if not os.path.isfile (licensePath): utils.log (True, 'Error: missing license reference file\n') return utils.log (True, '{} (TM) Python to JavaScript Small Sane Subset Transpiler Version {}\n', __base__.__envir__.transpiler_name.capitalize (), __base__.__envir__.transpiler_version) utils.log (True, 'Copyright (C) Geatec Engineering. License: Apache 2.0\n\n') utils.commandArgs.parse () if utils.commandArgs.license: with open (licensePath) as licenseFile: bar = 80 * '*' utils.log (True, '\n{}\n\n', bar) utils.log (True, '{}\n', licenseFile.read ()) utils.log (True, '{}\n\n', bar) if not utils.commandArgs.source: return if utils.commandArgs.run: with open (utils.commandArgs.source) as sourceFile: exec (sourceFile.read ()) else: try: compiler.Program (compilerPath) except utils.Error as error: utils.log (True, '\n{}\n', error) # Don't log anything else, even in verbose mode, since this would only be confusing if utils.commandArgs.dextex: utils.log (True, '{}\n', traceback.format_exc ()) except Exception as exception: utils.log (True, '\n{}', exception) # Have to log something else, because a general exception isn't informative enough utils.log (True, '{}\n', traceback.format_exc ()) utils.log (True, '\nReady\n')
def main(): licensePath = '{}/{}'.format(transpilerDir, 'license_reference.txt') if not os.path.isfile(licensePath): utils.log(True, 'Error: missing license reference file\n') return exitNoLicense utils.log( True, '{} (TM) Python to JavaScript Small Sane Subset Transpiler Version {}\n', __base__.__envir__.transpiler_name.capitalize(), __base__.__envir__.transpiler_version) utils.log(True, 'Copyright (C) Geatec Engineering. License: Apache 2.0\n\n') utils.commandArgs.parse() if utils.commandArgs.license: with open(licensePath) as licenseFile: bar = 80 * '*' utils.log(True, '\n{}\n\n', bar) utils.log(True, '{}\n', licenseFile.read()) utils.log(True, '{}\n\n', bar) if not utils.commandArgs.source: return exitSourceNotGiven # Should never be here, dealth with by command arg checks already if utils.commandArgs.run: try: with open(utils.commandArgs.source) as sourceFile: exec(sourceFile.read()) return exitSuccess except Exception as exception: utils.log( True, 'Error: cannot run {} using CPython: {}\n'.format( utils.commandArgs.source, str(exception).replace(' (<string>', '').replace(')', ''))) return exitCannotRunSource else: try: compiler.Program(compilerPath) return exitSuccess except utils.Error as error: utils.log(True, '\n{}\n', error) # Don't log anything else, even in verbose mode, since this would only be confusing if utils.commandArgs.dextex: utils.log(True, '{}\n', traceback.format_exc()) return exitSpecificCompileError except Exception as exception: utils.log(True, '\n{}', exception) # Have to log something else, because a general exception isn't informative enough utils.log(True, '{}\n', traceback.format_exc()) return exitGeneralCompileError
def main(): exitCode = exitCommandArgsError def exitHandler(): if exitCode == exitSuccess: utils.log(True, '\nReady\n') else: utils.log(True, '\nAborted\n') atexit.register(exitHandler) def setExitCode(anExitCode): nonlocal exitCode exitCode = anExitCode return exitCode try: __envir__ = utils.Any() with tokenize.open( f'{modulesDir}/org/transcrypt/__envir__.js') as envirFile: exec(envirFile.read()) __envir__.executor_name = __envir__.interpreter_name utils.log( True, '{} (TM) Python to JavaScript Small Sane Subset Transpiler Version {}\n', __envir__.transpiler_name.capitalize(), __envir__.transpiler_version) utils.log(True, 'Copyright (C) Geatec Engineering. License: Apache 2.0\n\n') utils.log(True, '\n') licensePath = '{}/{}'.format(transpilerDir, 'license_reference.txt') if not os.path.isfile(licensePath): utils.log(True, 'Error: missing license reference file\n') return setExitCode(exitNoLicense) utils.commandArgs.parse() if utils.commandArgs.license: with open(licensePath) as licenseFile: bar = 80 * '*' utils.log(True, '\n{}\n\n', bar) utils.log(True, '{}\n', licenseFile.read()) utils.log(True, '{}\n\n', bar) if utils.commandArgs.star: webbrowser.open('https://github.com/qquick/Transcrypt') if not utils.commandArgs.source: return setExitCode( exitSourceNotGiven ) # Should never be here, dealth with by command arg checks already # Prepend paths that are needed by transpiled or executed user code, since they have to be searched first # So user code favors Transcrypt modules over CPython modules extraDirs = utils.commandArgs.xpath.replace( '#', ' ').split('$') if utils.commandArgs.xpath else [] sourcePath = utils.commandArgs.source.replace( '\\', '/' ) # May be absolute or relative, in the latter case it may or may not specify a directory if '/' in sourcePath: # If directory specified sourceDir = sourcePath.rsplit('/', 1)[0] # Use it as source directory else: # Else sourceDir = os.getcwd().replace( '\\', '/') # Use current working directory as source directory projectDirs = [sourceDir] + extraDirs sys.path[0:0] = projectDirs global transpilationDirs transpilationDirs[0:0] = projectDirs __symbols__ = utils.commandArgs.symbols.split( '$') if utils.commandArgs.symbols else [] if utils.commandArgs.complex: __symbols__.append('__complex__') if utils.commandArgs.sform: __symbols__.append('__sform__') if utils.commandArgs.xtiny: __symbols__.append('__xtiny__') __symbols__.append('__py{}.{}__'.format(*sys.version_info[:2])) if utils.commandArgs.esv: __symbols__.append('__esv{}__'.format(utils.commandArgs.esv)) else: __symbols__.append('__esv{}__'.format( utils.defaultJavaScriptVersion)) # Import (ignored when transpiling) late, since commandArgs must be set already from org.transcrypt.stubs.browser import __set_stubsymbols__ # Make symbols available to CPython, seems that exec can't do that directly __set_stubsymbols__(__symbols__) if utils.commandArgs.run: try: with open(utils.commandArgs.source + '.py') as sourceFile: exec(sourceFile.read(), globals(), locals()) return setExitCode(exitSuccess) except Exception as exception: utils.log( True, 'Error: cannot run {} using CPython: {}\n'.format( utils.commandArgs.source, str(exception).replace(' (<string>', '').replace(')', ''))) utils.log(True, traceback.format_exc()) return setExitCode(exitCannotRunSource) else: try: compiler.Program(transpilationDirs, __symbols__, __envir__) return setExitCode(exitSuccess) except utils.Error as error: utils.log(True, '\n{}\n', error) # Don't log anything else, even in verbose mode, since this would only be confusing if utils.commandArgs.dextex: utils.log(True, '{}\n', traceback.format_exc()) return setExitCode(exitSpecificCompileError) except Exception as exception: utils.log(True, '\n{}', exception) # Have to log something else, because a general exception isn't informative enough utils.log(True, '{}\n', traceback.format_exc()) return setExitCode(exitGeneralCompileError) except utils.CommandArgsError: return setExitCode(exitCommandArgsError) except utils.CommandArgsExit: return setExitCode(exitSuccess)
def logHeader (sourcePath): utils.log (True, 'Performing static type validation on application: {}\n', sourcePath)
def saveJavascript (self,): utils.log (False, 'Saving precompiled module: {}\n', self.metadata.targetPath) with utils.create (self.metadata.targetPath) as aFile: aFile.write (self.targetCode)
def __main__(): # TODO: Avoid this, accept a base path on the CLI. programDir = os.getcwd().replace('\\', '/') utils.log(True, '{} (TM) Python to JavaScript Small Sane Subset Transpiler Version {}\n', __base__.__envir__.transpilerName.capitalize(), __base__.__envir__.transpilerVersion ) utils.log(True, 'Copyright (C) Geatec Engineering. License: Apache 2.0\n\n') utils.commandArgs.parse() if utils.commandArgs.license: bar = 80 * '=' utils.log (True, '\n{}\n\n', bar) utils.log (True, '{}\n', pkg_resources.resource_string('transcrypt', 'license_reference.txt').decode('utf8')) utils.log (True, '{}\n\n', bar) if not utils.commandArgs.source: exit (0) if utils.commandArgs.run: with open(utils.commandArgs.source) as sourceFile: exec( 'import sys\n' + #'sys.path [0] = sys.path [1 : ]\n' + # "import transcrypt" should refer to library rather than to this file #'sys.path.append (\'{}\')\n'.format (modulesDir) + sourceFile.read() ) exit(0) try: compiler.Program([programDir, modulesDir]) except utils.Error as error: utils.log(True, '\n{}\n', error) # Don't log anything else, even in verbose mode, since this would only be confusing if utils.debug: utils.log(True, '{}\n', traceback.format_exc()) except Exception as exception: utils.log(True, '\n{}', exception) # Have to log something else, because a general exception isn't informative enough utils.log(False, '{}\n', traceback.format_exc()) utils.log(True, 'Ready\n')
def run (sourcePath): try: utils.log (True, 'Performing static type validation on application: {}\n', sourcePath) validationMessages = api.type_validator.validate ([sourcePath]) if validationMessages: oldFileName = '' for validationMessage in validationMessages: if isinstance (validationMessage, api.StaticTypingError): if validationMessage.file_name != oldFileName: utils.log (True, '\tFile {}\n', validationMessage.file_name) oldFileName = validationMessage.file_name utils.log (True, '\t\tLine {}: {}\n', validationMessage.line_nr, validationMessage.description) elif isinstance (validationError, api.CompilationError): utils.log (True, '\t{}'.format (message)) else: util.log (True, '\tUnknown error') utils.log (True, '\n') except Exception as exception: utils.log (False, traceback.format_exc ()) raise exception
import sys import traceback sys.path[0] = sys.path[0] + '/modules' from org.transcrypt import __base__ from org.transcrypt import utils from org.transcrypt import compiler programDir = os.getcwd().replace('\\', '/') transpilerDir = os.path.dirname(os.path.abspath(__file__)).replace('\\', '/') modulesDir = '{}/modules'.format(transpilerDir) licencePath = '{}/{}'.format(transpilerDir, '../license_reference.txt') if not os.path.isfile(licencePath): utils.log(True, 'Error: missing license reference file\n') exit(1) utils.log( True, '{} (TM) Python to JavaScript Small Sane Subset Transpiler Version {}\n', __base__.__envir__.transpilerName.capitalize(), __base__.__envir__.transpilerVersion) utils.log(True, 'Copyright (C) Geatec Engineering. License: Apache 2.0\n\n') utils.commandArgs.parse() if utils.commandArgs.license: with open(licensePath) as licenseFile: bar = 80 * '=' utils.log(True, '\n{}\n\n', bar)