### Install pyjsparser Source: https://github.com/piotrdabkowski/pyjsparser/blob/master/README.md Use pip to install the library. ```bash pip install pyjsparser ``` -------------------------------- ### Parse regular expressions Source: https://context7.com/piotrdabkowski/pyjsparser/llms.txt Demonstrates handling of regex literals and their flags within the AST. ```python from pyjsparser import parse # Parse regex literal ast = parse('var pattern = /[a-z]+/gi;') regex = ast['body'][0]['declarations'][0]['init'] print(regex['type']) # 'Literal' print(regex['regex']['pattern']) # '[a-z]+' print(regex['regex']['flags']) # 'gi' # Parse regex in context ast = parse('var isEmail = /^\\w+@\\w+\\.\\w+$/.test(email);') call_expr = ast['body'][0]['declarations'][0]['init'] print(call_expr['type']) # 'CallExpression' print(call_expr['callee']['object']['regex']['pattern']) # '^\\w+@\\w+\\.\\w+$' ``` -------------------------------- ### Convert AST nodes to dictionaries Source: https://context7.com/piotrdabkowski/pyjsparser/llms.txt Shows the use of node_to_dict to ensure AST nodes are represented as standard Python dictionaries. ```python from pyjsparser import PyJsParser from pyjsparser.std_nodes import node_to_dict, Node # The parse method already returns dict by default parser = PyJsParser() result = parser.parse('var x = 1;') print(type(result)) # # Convert nested node structures ast = parser.parse('var obj = {a: 1, b: 2};') # All nested nodes are converted to dictionaries print(type(ast['body'][0]['declarations'][0]['init'])) # ``` -------------------------------- ### parse() Function Source: https://context7.com/piotrdabkowski/pyjsparser/llms.txt The primary entry point for parsing JavaScript code strings into an AST dictionary. ```APIDOC ## parse(code) ### Description Parses a JavaScript code string and returns a dictionary representing the complete AST of the program following the ESTree specification. ### Parameters #### Request Body - **code** (string) - Required - The JavaScript source code to parse. ### Response #### Success Response (200) - **AST** (dict) - A dictionary representing the ESTree-compliant Abstract Syntax Tree. ``` -------------------------------- ### Parse ES6 let and const declarations Source: https://context7.com/piotrdabkowski/pyjsparser/llms.txt Demonstrates parsing lexical declarations and accessing the 'kind' property of VariableDeclaration nodes. ```python from pyjsparser import parse # Parse let declaration ast = parse('let counter = 0;') decl = ast['body'][0] print(decl['type']) # 'VariableDeclaration' print(decl['kind']) # 'let' # Parse const declaration ast = parse('const PI = 3.14159;') decl = ast['body'][0] print(decl['kind']) # 'const' # Parse multiple declarations ast = parse('let a = 1, b = 2, c = 3;') print(len(ast['body'][0]['declarations'])) # 3 ``` -------------------------------- ### Parse object literals with methods Source: https://context7.com/piotrdabkowski/pyjsparser/llms.txt Covers parsing of getters, setters, and computed property names within object expressions. ```python from pyjsparser import parse # Parse object with getter and setter code = ''' var person = { _name: "John", get name() { return this._name; }, set name(value) { this._name = value; } }; ''' ast = parse(code) obj = ast['body'][0]['declarations'][0]['init'] print(obj['type']) # 'ObjectExpression' for prop in obj['properties']: print(f"Kind: {prop['kind']}, Key: {prop['key']['name']}") # Output: # Kind: init, Key: _name # Kind: get, Key: name # Kind: set, Key: name # Parse object with computed property names ast = parse('var obj = { [dynamicKey]: "value" };') prop = ast['body'][0]['declarations'][0]['init']['properties'][0] print(prop['computed']) # True ``` -------------------------------- ### Parse JavaScript code Source: https://github.com/piotrdabkowski/pyjsparser/blob/master/README.md Import the parse function to convert JavaScript source code into an AST. ```python >>> from pyjsparser import parse >>> parse('var $ = "Hello!"') { "type": "Program", "body": [ { "type": "VariableDeclaration", "declarations": [ { "type": "VariableDeclarator", "id": { "type": "Identifier", "name": "$" }, "init": { "type": "Literal", "value": "Hello!", "raw": '"Hello!"' } } ], "kind": "var" } ] } ``` -------------------------------- ### Parse JavaScript control flow statements Source: https://context7.com/piotrdabkowski/pyjsparser/llms.txt Illustrates parsing various control flow constructs including loops, conditionals, and try-catch blocks. ```python from pyjsparser import parse # Parse if-else statement ast = parse('if (x > 0) { return "positive"; } else { return "non-positive"; }') if_stmt = ast['body'][0] print(if_stmt['type']) # 'IfStatement' print(if_stmt['test']['type']) # 'BinaryExpression' print(if_stmt['test']['operator']) # '>' # Parse for loop ast = parse('for (var i = 0; i < 10; i++) { console.log(i); }') for_stmt = ast['body'][0] print(for_stmt['type']) # 'ForStatement' print(for_stmt['init']['declarations'][0]['id']['name']) # 'i' # Parse for-in loop ast = parse('for (var key in obj) { console.log(key); }') forin_stmt = ast['body'][0] print(forin_stmt['type']) # 'ForInStatement' # Parse try-catch-finally code = ''' try { riskyOperation(); } catch (error) { handleError(error); } finally { cleanup(); } ''' ast = parse(code) try_stmt = ast['body'][0] print(try_stmt['type']) # 'TryStatement' print(try_stmt['handler']['param']['name']) # 'error' print(try_stmt['finalizer'] is not None) # True ``` -------------------------------- ### Parse JavaScript with parse() Source: https://context7.com/piotrdabkowski/pyjsparser/llms.txt Use the module-level parse function to convert JavaScript strings into an AST dictionary. ```python from pyjsparser import parse # Parse a simple variable declaration ast = parse('var greeting = "Hello, World!"') print(ast) # Output: # { # 'type': 'Program', # 'body': [{ # 'type': 'VariableDeclaration', # 'declarations': [{ # 'type': 'VariableDeclarator', # 'id': {'type': 'Identifier', 'name': 'greeting'}, # 'init': {'type': 'Literal', 'value': 'Hello, World!', 'raw': '"Hello, World!"'} # }], # 'kind': 'var' # }] # } # Parse a function declaration with expressions code = ''' function add(a, b) { return a + b; } var result = add(5, 3); ''' ast = parse(code) print(ast['body'][0]['type']) # 'FunctionDeclaration' print(ast['body'][0]['id']['name']) # 'add' print(ast['body'][0]['params'][0]['name']) # 'a' ``` -------------------------------- ### PyJsParser Class Source: https://context7.com/piotrdabkowski/pyjsparser/llms.txt A class-based parser that maintains internal state, allowing for efficient reuse when parsing multiple scripts. ```APIDOC ## PyJsParser.parse(code) ### Description Parses a JavaScript code string using a persistent parser instance. ### Parameters #### Request Body - **code** (string) - Required - The JavaScript source code to parse. ### Response #### Success Response (200) - **AST** (dict) - A dictionary representing the ESTree-compliant Abstract Syntax Tree. ``` -------------------------------- ### Parse ES6 template literals Source: https://context7.com/piotrdabkowski/pyjsparser/llms.txt Shows how to extract template literal types and embedded expressions from the AST. ```python from pyjsparser import parse # Parse simple template literal ast = parse('var str = `Hello World`;') template = ast['body'][0]['declarations'][0]['init'] print(template['type']) # 'TemplateLiteral' print(template['quasis'][0]['value']['cooked']) # 'Hello World' # Parse template literal with expressions ast = parse('var greeting = `Hello, ${name}!`;') template = ast['body'][0]['declarations'][0]['init'] print(len(template['expressions'])) # 1 print(template['expressions'][0]['type']) # 'Identifier' print(template['expressions'][0]['name']) # 'name' ``` -------------------------------- ### Parse JavaScript with PyJsParser class Source: https://context7.com/piotrdabkowski/pyjsparser/llms.txt Utilize the PyJsParser class to maintain state and reuse the parser instance across multiple operations. ```python from pyjsparser import PyJsParser # Create a parser instance for reuse parser = PyJsParser() # Parse multiple JavaScript snippets scripts = [ 'var x = 10;', 'function greet(name) { return "Hello " + name; }', 'var arr = [1, 2, 3].map(function(n) { return n * 2; });' ] for script in scripts: ast = parser.parse(script) print(f"Script type: {ast['type']}") print(f"Number of statements: {len(ast['body'])}") print() # Access specific AST nodes ast = parser.parse('var obj = { name: "test", value: 42 };') obj_expression = ast['body'][0]['declarations'][0]['init'] print(obj_expression['type']) # 'ObjectExpression' print(len(obj_expression['properties'])) # 2 # Parse complex expressions with the test helper parser.test('var complex = (a + b) * (c - d);') # Pretty prints the AST structure ``` -------------------------------- ### JsSyntaxError Exception Source: https://context7.com/piotrdabkowski/pyjsparser/llms.txt Exception class raised when the parser encounters invalid JavaScript syntax. ```APIDOC ## JsSyntaxError ### Description Raised when the parser encounters invalid JavaScript syntax. Provides line number and position information for debugging. ### Response #### Error Response - **message** (string) - Contains the line number and description of the syntax error. ``` -------------------------------- ### Handle JsSyntaxError Source: https://context7.com/piotrdabkowski/pyjsparser/llms.txt Catch syntax errors during parsing to retrieve line and position information. ```python from pyjsparser import parse, JsSyntaxError # Handle syntax errors gracefully code_samples = [ 'var x = 10;', # Valid 'var = 5;', # Invalid - missing identifier 'function() {}', # Invalid - missing function name 'var x = {a: 1, b: };' # Invalid - trailing comma with no value ] for code in code_samples: try: ast = parse(code) print(f"Valid: {code[:30]}...") except JsSyntaxError as e: print(f"Syntax Error: {e}") # Example output for invalid code: # Syntax Error: Line 1: Unexpected token = # Detailed error handling try: parse(''' function test() { if (true) { return // Missing closing brace } ''') except JsSyntaxError as error: print(f"Parse failed: {error}") ``` -------------------------------- ### Parse ES6 Arrow Functions Source: https://context7.com/piotrdabkowski/pyjsparser/llms.txt Handle ArrowFunctionExpression nodes, including support for concise and block body syntax. ```python from pyjsparser import parse # Parse arrow function with concise body ast = parse('var double = x => x * 2;') arrow_fn = ast['body'][0]['declarations'][0]['init'] print(arrow_fn['type']) # 'ArrowFunctionExpression' print(arrow_fn['expression']) # True (concise body) print(arrow_fn['params'][0]['name']) # 'x' # Parse arrow function with block body ast = parse('var add = (a, b) => { return a + b; };') arrow_fn = ast['body'][0]['declarations'][0]['init'] print(arrow_fn['expression']) # False (block body) print(arrow_fn['body']['type']) # 'BlockStatement' # Parse arrow function with no parameters ast = parse('var getTime = () => Date.now();') arrow_fn = ast['body'][0]['declarations'][0]['init'] print(len(arrow_fn['params'])) # 0 ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.