Skip to content

[core] RFC: Analyzing embedded snippets from other languages #237

Open

Description

@jsotuyod

Problem

Supported languages such as JSP (and unsupported languages such as PHP, VisualForce and Lightning) allow to embed snippets of code in supported languages such as JavaScript (and unsupported languages such as CSS).

However, the parser and rules applied per file are determined by file extension. That means, that given a project using a ruleset with both JS rules and JSP rules, inconsistent rule application can occur:

File test.jsp, jsp rules applied:

<script href="/test.js"></script> <!-- test.js will be parsed and analyzed by JS rules -->
<script> <!-- This snippet may contain whatever, no JS rules will ever check it -->
var test = "something";
</script>

Objective

Embedded code snippets should be parsed and analyzed the same way stand-alone files are.

Proposal

Each language parser should, upon detecting an embeded snippet, make sure to call a proper PMD helper with the snippet contents & detected language to use. Such helper will:

  1. Make sure the detected language is supported, showing a warning otherwise
  2. Synchronously start a new PMD analysis using the same ruleset on the contents of the snippet. This way the same rules are applied on the snippet that are applied to standalone files. The source file and line numbers should not be altered. It may be of use to allow the Context to know it's an embedded snippet.
  3. Resume parsing of the holder file as is.

By having this logic in the parser, it's enabled by default for all supported languages, and guaranteed to occur only once per file.

Difficulties

The holder languages tend to allow to mix the embedded snippets with expressions in the original language, such as:

<script>
var s = "<c:out val="${name}"/>";
</script>

These should probably be analyzed from the perspective of both languages.

Regarding the holder language, these expressions are of interest to be analyzed on their own (ie: don't allow unescaped values). They should probably be transformed into child nodes of the <script> tag in the AST which rules can visit and report on.

Regarding to the snippet, these expressions should be either removed or replaced with literals that won't change the syntax. This way, the embedded language will have no idea those values came from the holder language. This could be challenging, since the developer could use them anywhere, and we don't want these placeholders introducing false positives in the embedded language ruleset. For instance:

var s = "${stringVar}";
var i = ${intVar};

${methodNameSentFromController}();
${anotherVar}[4] = "test me";

What value could be passed as placeholder for all 4 alternatives? From a parsers' perspective, the only alternative I can think of valid in all 4 contexts is (function() {}). Where the last alternative would produce a runtime error, but the parser, and available rules will probably never notice.

These snippets are specific to each embedded language. This however means:

  1. The embedded language opts-in to being embedded, providing a placeholder factory.
  2. The holder language opts-in to parsing and analyzing embedded snippets by handling them properly in their parsers.

Also of note, since the embedded language has no idea that those are placeholders coming from a host language (as to not modify the parsers for the embedded languages), this means we can go as far as enforcing:

<script>
var userData = '{! JSENCODE(userData)}';
</script>

but not actually enforcing:

<script>
var userData = JSON.parse('{! JSENCODE(userData)}');
</script>

I'm not really happy with this, but can't think of a better way around it short of having he embedded language also know of the holder language and this means making changes to the parsers that will be hard to mantain and extend in the future.

@adangel @sgorbaty I'd love to listen to your feedback.

Activity

  1. added
    an:enhancement
    a:suggestion
    on Feb 5, 2017
  2. adangel commented on Feb 5, 2017

    @adangel
    Member

    @jsotuyod Thanks for taking the time to write this up!
    This looks very good. Just a few comments:

    • I'd like to have a step-by-step approach: solving first the simple case: the embedded language as is, without placeholders. Till this works, we can refine the more difficult case with placeholder factory...

    • The detected language... PMD itself really just looks at the file extension. As we have in this case no file, the holder language needs to provide a hint. I guess, we should add supported ContentTypes/MediaTypes for each language module. That way, the holder language (being JSP/HTML) could just provide the type attribute (<script type="text/javascript">...) to PMD. I think, only the holder language will be able to say, what kind of embedded language we are looking at.

    • "Synchronously start a new PMD analysis". Not sure about this one. At the moment, I see the embedded snippet as just another file, added to the list of file yet to be analyzed. However, there is one use case that comes into my mind: If the embedded snippet contains parse errors, then we could consider the holding file also being invalid... having PMD called synchronously allows us to drop this file earlier in the process (no need to run any rules on it).

    • About the ruleset: "same ruleset" exactly. Just to be clear: The ruleset contains rules for both languages, the holder language and the embedded language.

    • "By having this logic in the parser, it's enabled by default for all supported languages" +1. However, since the way how the snippet is being embedded depends on the holder language, each language, that supports embedded languages, needs to have its parser adjusted to extract the snippet...

    Hm... I'm thinking about your example:

    <script>
    var userData = JSON.parse('{! JSENCODE(userData)}');
    </script>
    

    Do I understand it correctly, that the JS parser would see something like this?

    var userData = JSON.parse((function(){}));
    

    What if the holder language would replace the placeholder with some well-known constant? E.g. var userData = JSON.parse('JSON_ENCODED_STRING');. This would require the holding language to parse the placeholders and provide simplified replacements. The holding language parser would then need to provide for each embedded language a specific place holder factory. Ok, the embedded language can provide a default factory, but only the holding language understands the placeholders. Having the constants in the embedded snippet, rules can be created that are triggered by literals. However, these rules would then be tightly coupled to the combinations holding language+embedded language and most likely would be not generic enough to be used outside this use case...

    Update: Here's the description of the JSENCODE function:
    https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_variables_functions.htm

  3. jsotuyod commented on Feb 5, 2017

    @jsotuyod
    MemberAuthor

    The detected language... PMD itself really just looks at the file extension. As we have in this case no file, the holder language needs to provide a hint. I guess, we should add supported ContentTypes/MediaTypes for each language module. That way, the holder language (being JSP/HTML) could just provide the type attribute (<script type="text/javascript">...) to PMD. I think, only the holder language will be able to say, what kind of embedded language we are looking at.

    Yes, that's exactly what I was after. The holder language parser will have to say which language it believes the embedded code corresponds to. Usually taken from a parsed attribute (<script type="....">) or a default.

    "Synchronously start a new PMD analysis". Not sure about this one. At the moment, I see the embedded snippet as just another file, added to the list of file yet to be analyzed. However, there is one use case that comes into my mind: If the embedded snippet contains parse errors, then we could consider the holding file also being invalid... having PMD called synchronously allows us to drop this file earlier in the process (no need to run any rules on it).

    The reason for synchronous analysis is that the file we are reporting on is the same, and we need to keep true to this promise

    As for a fail-all on any embedded language failure... I'm not sure that's a positive, specially if we acknowledge parsing of embedded snippets can be problematic due to the mixed nature of the code. Reporting such cases independently, aborting parsing the embedded snippet, and carrying on is probably best for users, while keeping visibility on such issues so we may fix them.

    About the ruleset: "same ruleset" exactly. Just to be clear: The ruleset contains rules for both languages, the holder language and the embedded language.

    That's exactly what I was after.

    "By having this logic in the parser, it's enabled by default for all supported languages" +1. However, since the way how the snippet is being embedded depends on the holder language, each language, that supports embedded languages, needs to have its parser adjusted to extract the snippet...

    That's right. Currently the JSP parser is already capable of this.

    Do I understand it correctly, that the JS parser would see something like this?

    var userData = JSON.parse((function(){}));

    That's right. Not semantically correct, but syntactically sound.

    What if the holder language would replace the placeholder with some well-known constant? E.g. var userData = JSON.parse('JSON_ENCODED_STRING');. This would require the holding language to parse the placeholders and provide simplified replacements. The holding language parser would then need to provide for each embedded language a specific place holder factory. Ok, the embedded language can provide a default factory, but only the holding language understands the placeholders. Having the constants in the embedded snippet, rules can be created that are triggered by literals. However, these rules would then be tightly coupled to the combinations holding language+embedded language and most likely would be not generic enough to be used outside this use case...

    I'm not sure I follow thoroughly. The holder language parses and should able to analyze the the holder language pieces (ie: {! JSENCODE(userData)}, jsp currently parses EL nodes, but not within <script> tags). The embedded language can't parse these, it needs to find something that at the very least, is syntactically correct (that is, doesn't produce a paring error). Having the holder language decide on the placeholder is not a good idea for maintainability / extensibility. Having the embedded language provide it is probably much better. A default that fits all / most is good to keep things simple, we may have that factory be able to produce placeholders per-type (string literal, numeric literal, etc.), but I don't think that either the holder language will have enough info to make such decision at the parser level, nor that it would make much difference to the embedded language analysis.

    The one thing where I believe the embedded language can benefit from something more elaborate than a placeholder is actually knowing that the data is coming from another language and may need to be parsed / treated differently.... maybe this can be achieved by using a placeholder that contains a special token (as in JavaCC's special tokens, usually comments), that do not participate in parsing (that is, can be placed anywhere, and are ignored unless specially looked upon) by a rule that cares for these thing.

  4. sgorbaty commented on Feb 9, 2017

    @sgorbaty
    Contributor

    Hi @jsotuyod and @adangel ,

    Regarding replacement of tokens inside the embedded language. Ideally, I'd like to save the syntax used in the placeholder to be analyzed by the target language. That will require the owners of the parser that supports placeholders do most of the work. E.g. 4 use cases that you used previously

    I think you were very close, but if I may suggest, using IFFY we could make it a legal JS syntactically but it may not run.

    var abc = ${someVar}; => var abc = (function() { return '${someVar}' })();

    var abc = "${someVar};" => var abc = (function() { return '"${someVar}"' })();

    ${methodNameSentFromController}(); => (function() { return '${methodNameSentFromController}' })()();

    ${anotherVar}[4] = "test me"; => (function() { return '${anotherVar}' })()[4] = "test me";

    var abc = {!someVar}; => var abc = (function() { return '{!someVar}' })();

  5. jsotuyod commented on Feb 9, 2017

    @jsotuyod
    MemberAuthor

    @sgorbaty the quoting can be tricky....

    • JS for instance allows both single and double quotes (and since ecmascript 5, even backsticks). JS rules may be applied to favor one or the other, choosing one at parser level, without knowledge of the rules means we are introducing false positives to such rules.
    • The contents to be quoted may contain quotes itself, so we would need to have the embedded language know about string escaping too (ie: `var abc = '<c:out value='prop'/>';)
    • In your examples, on the second scenario, you are taking into the placeholder actually more than the holder language variable, you are taking the quotes. Being able to know how / when to do this would require the holder language to actually be able to parse the embedded language itself. It should probably be: var abc = "${someVar}"; => var abc = "(function() { return '${someVar}' })()";
  6. added
    a:RFC
    and removed
    a:suggestion
    on Jun 17, 2017
  7. added this to the 7.x milestone on Jan 23, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    a:RFCan:enhancement

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions